我一直在努力在现有的XML代码中添加一些XML代码,以便通过python与REST API进行交互。
这是我想出的代码:
import xml.etree.ElementTree as ET
xml_str = """<entry>
<id>com.scur.type.string.1846</id>
<title>Global Bobo</title>
<type>com.string</type>
<listType>string</listType>
<link href="https://internalonly" rel="self"/>
<content>
<list version="1">
<description>SmartL both sides of the entry</description>
<content>
<listEntry>
<entry>aaaaaaaaaaaaaaaaa</entry>
<description>description for aaaaaaaaaaaaaaaa</description>
</listEntry>
<listEntry>
<entry>bbbbbbbbbbbbbbbb</entry>
<description />
</listEntry>
<listEntry>
<entry>ADDEDVIAREST.COM</entry>
<description />
</listEntry>
<listEntry>
<entry>ADDEDVIA-PYTHON-REST.COM</entry>
<description />
</listEntry>
</content>
</list>
</content>
</entry>"""
# build the tree
tree = ET.fromstring(xml_str)
# create the file structure
data = ET.Element('listEntry')
entry = ET.SubElement(data, 'entry')
description = ET.SubElement(data, 'description')
entry.text = 'blabla.com'
description.text = 'weehaaw'
for row in tree.iterfind('.//content'):
row.append(data)
print(ET.tostring(tree))
您可能会注意到,输出并不令人满意,我创建的元素被插入到XML的多个位置,我认为这是因为XML中的字段名称相同。
我的目标是在正确的“内容”(位于其他条目的下方)中插入一个带有条目和描述的新侦听器。有什么办法可以做到吗?
如果有任何帮助(公司规则),我会使用python 2.7。
谢谢!
答案 0 :(得分:0)
这是罪魁祸首:
for row in tree.iterfind('.//content'):
row.append(data)
您要添加到每个实例。您可以删除此标签,而只需查找第二个/内部<content>
标签,然后在其中使用ET.SubElement
。
content = tree.findall('.//content')[1] # Just get the second instance.
data = ET.SubElement(content, 'listEntry')
entry = ET.SubElement(data, 'entry')
description = ET.SubElement(data, 'description')
entry.text = 'blabla.com'
description.text = 'weehaaw'
这应仅将data
添加到内部实例。
<entry>
<id>com.scur.type.string.1846</id>
<title>Global Bobo</title>
<type>com.string</type>
<listType>string</listType>
<link href="https://internalonly" rel="self" />
<content>
<list version="1">
<description>SmartL both sides of the entry</description>
<content>
<listEntry>
<entry>aaaaaaaaaaaaaaaaa</entry>
<description>description for aaaaaaaaaaaaaaaa</description>
</listEntry>
<listEntry>
<entry>bbbbbbbbbbbbbbbb</entry>
<description />
</listEntry>
<listEntry>
<entry>ADDEDVIAREST.COM</entry>
<description />
</listEntry>
<listEntry>
<entry>ADDEDVIA-PYTHON-REST.COM</entry>
<description />
</listEntry>
<listEntry>
<entry>blabla.com</entry>
<description>weehaaw</description>
</listEntry>
</content>
</list>
</content>
</entry>