使用元素树向子树添加新元素

Adding new element to a subtree using Element Tree

我正在努力使用 ElementTree 将数据添加到 子树 ;我的 XML 文件如下所示:

通常,我会使用 et.SubElement 添加新标签,但它会写在 "file" 下(i.e. = et.SubElement(tree.getroot(), 'new tag') 然后我会使用 .text 添加我需要的内容。属性 . 等等 ).

我想在路径中添加另一个 "instance":file/all_instances,这是我正在努力解决的问题。

总之,子树"all_instance"下应该还有另一个"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 元素结构构建为字符串,然后将其转换为 Element 或将其 append() or 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>