首页 > 解决方案 > 使用元素树向子树添加新元素

问题描述

我正在努力使用 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>

标签: pythonxmlelementtree

解决方案


而不是使用:

et.SubElement(tree.getroot(), 'instance')

你可以使用:

et.SubElement(tree.find("./ALL_INSTANCES"), 'instance')

您还可以instance先将新元素结构构建为字符串,然后将其转换为 an Elementand 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>

推荐阅读