背景:我试图用从web服务端点检索的元数据充实XML报告。报告列出了文本模块和图形,每个图形都有几个分辨率。我无法为每个分辨率添加元数据。在
问题:问题简化了。在
from lxml import etree as ET
myxml = """\
<report>
<object id="foo">
<reportitems>
<reportitem id="1"/>
<reportitem id="2"/>
<reportitem id="3"/>
</reportitems>
</object>
</report>
"""
report = ET.fromstring(myxml)
test = ET.Element("test", foo="bar")
for r in report.findall("object/reportitems/reportitem"):
r.append(test)
我得到这个输出:
^{pr2}$现在,如果我像这样修改代码(使用相同的XML片段):
report = ET.fromstring(myxml)
myElements = [ET.Element("test1"), ET.Element("test2"), ET.Element("test3")]
counter = 0
for r in report.findall("object/reportitems/reportitem"):
r.append(myElements[counter])
counter += 1
…然后我得到这个输出:
<report>
<object id="foo">
<reportitems>
<reportitem id="1"><test1/></reportitem>
<reportitem id="2"><test2/></reportitem>
<reportitem id="3"><test3/></reportitem>
</reportitems>
</object>
</report>
为什么不能将相同(相同)的元素作为子元素添加到我迭代的多个元素中?在
此行为在lxml tutorial中描述:
^{pr2}$构造函数
ET.Element
中的问题,每次调用只创建一个节点。您可以更改节点的父节点,但ET.Element
将只有一个。您可以在循环中多次创建ET.Element
,以避免此问题:相关问题 更多 >
编程相关推荐