python - 使用元素树向子树添加新元素
问题描述
我正在努力使用 ElementTree向子树添加数据;我的 XML 文件如下所示:
通常,我会使用 et.SubElement 添加一个新标签,但它会写在“文件”下(i.e. = et.SubElement(tree.getroot(), 'new tag')
然后我会使用 .text .attrib .etc 等添加我需要的内容)。
我想在路径中添加另一个“实例”:file/all_instances,这是我正在努力解决的问题。
总之,在子树“all_instance”下应该有另一个“实例”,具有相同的结构(ID、Start 等)。所以,我理想的输出是:
<instance>
<ID> .. </ID>
<start> ..</start>
<end>.. </end>
<code> ..</code>
</instance>
感谢您的帮助 :)
编辑:
这是我的 XML 文件:
<file>
<SESSION_INFO>
<start_time>2016-11-24 02:58:34.36 -0800</start_time>
</SESSION_INFO>
<ALL_INSTANCES>
<instance>
<ID>1</ID>
<start>18.8426378227</start>
<end>71.6020237264</end>
<code>Shot </code>
</instance>
<instance>
<ID>2</ID>
<start>139.4355198883</start>
<end>199.7319609211</end>
<code>Shot </code>
<label>
<text>Succ</text>
</label>
</instance>
<instance>
<ID>3</ID>
<start>237.4172365666</start>
<end>305.2507327285</end>
<code>Shot </code>
</instance>
</ALL_INSTANCES>
<ROWS>
<row>
<code>Shot </code>
<R>57000</R>
<G>57000</G>
<B>57000</B>
</row>
<row>
<code>Shot Succ</code>
<R>57000</R>
<G>57000</G>
<B>57000</B>
</row>
</ROWS>
</file>
解决方案
而不是使用:
et.SubElement(tree.getroot(), 'instance')
你可以使用:
et.SubElement(tree.find("./ALL_INSTANCES"), 'instance')
您还可以instance
先将新元素结构构建为字符串,然后将其转换为 an Element
and eitherappend()
或insert()
转换为ALL_INSTANCES
.
例子...
import xml.etree.ElementTree as ET
tree = ET.parse("input.xml")
new_instance = """<instance>
<ID> .. </ID>
<start> .. </start>
<end> .. </end>
<code> .. </code>
</instance>
"""
tree.find("./ALL_INSTANCES").append(ET.fromstring(new_instance))
print(ET.tostring(tree.getroot()).decode())
印刷...
<file>
<SESSION_INFO>
<start_time>2016-11-24 02:58:34.36 -0800</start_time>
</SESSION_INFO>
<ALL_INSTANCES>
<instance>
<ID>1</ID>
<start>18.8426378227</start>
<end>71.6020237264</end>
<code>Shot </code>
</instance>
<instance>
<ID>2</ID>
<start>139.4355198883</start>
<end>199.7319609211</end>
<code>Shot </code>
<label>
<text>Succ</text>
</label>
</instance>
<instance>
<ID>3</ID>
<start>237.4172365666</start>
<end>305.2507327285</end>
<code>Shot </code>
</instance>
<instance>
<ID> .. </ID>
<start> .. </start>
<end> .. </end>
<code> .. </code>
</instance></ALL_INSTANCES>
<ROWS>
<row>
<code>Shot </code>
<R>57000</R>
<G>57000</G>
<B>57000</B>
</row>
<row>
<code>Shot Succ</code>
<R>57000</R>
<G>57000</G>
<B>57000</B>
</row>
</ROWS>
</file>
推荐阅读
- javascript - 数据读取后打开或弹出新页面 id = 1 自动不刷新 - PHP & Javascripts
- python - 连接 dask 数据帧和 pandas 数据帧
- javascript - 解析查询从基于另一个关系的关系中排除对象
- java - 我有一个程序,我需要用户被询问是否要继续并每次都添加到总和中
- mysql - 按类别显示 MySQL 8 中的前 N 个分数且不重复
- ios - AudioKit:从 Podfile 的开发分支中提取
- python - 从嵌套字典中提取值出现的次数
- javascript - 先前隐藏的 div 上的按钮不起作用
- algorithm - 哪些数据结构/算法可以有效地将 DNF 表达式相互替换?
- sql - 分组结果的 SQL 查询帮助