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

标签 python xml elementtree

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

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

我想在路径中添加另一个“实例”: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 元素结构构建为字符串,然后将其转换为 Elementappend()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>

关于python - 使用元素树向子树添加新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58974713/

相关文章:

python - 打印 xml 节点 python xtree

python - 如何将字符串作为参数名称传递?

python - 多个阈值的混淆矩阵

javascript - 通过 Javascript、Jquery 或 Ajax 插入 XML 文件

android - 如何将超链接添加到首选项屏幕 (PreferenceActivity)

python - Beautiful Soup - `findAll` 没有捕获 SVG (`ElementTree` 中的所有标签)

Python ElementTree 发现不工作

python - 根据行数循环 Python 脚本

python - 为 jinja2 中的未定义属性引发异常

php - 如何在 PHP 中读取交错 XML 的子项