gpt4 book ai didi

python - 使用 lxml 将多个元素添加到 xml

转载 作者:太空宇宙 更新时间:2023-11-03 17:09:40 24 4
gpt4 key购买 nike

我想将一些子元素添加到 xml 树的父元素中。源 XML 是:

<catalog>
<element>
<collection_list />
</element>
<element>
<collection_list />
</element>
</catalog>

我在 python 3 中尝试过以下代码:

from lxml import etree
tree = etree.parse('source.xml')
root = tree.getroot()

elementCollections = tree.xpath('/catalog/element/collection_list')

for element in elementCollections:
childElement = etree.SubElement(element, "collection")
listOfElementCollections = ['c1', 'c2', 'c3']

for elementCollection in listOfElementCollections:
childElement.text = elementCollection

newtree = etree.tostring(tree, encoding='utf-8')
newtree = newtree.decode("utf-8")
print(newtree)

但不是:

<catalog>
<element>
<collection_list>
<collection>c1</collection>
<collection>c2</collection>
<collection>c3</collection>
</collection_list>
</element>
<element>
<collection_list>
<collection>c1</collection>
<collection>c2</collection>
<collection>c3</collection>
</collection_list>
</element>
</catalog>

我有这样的结果:

<catalog>
<element>
<collection_list>
<collection>c3</collection>
</collection_list>
</element>
<element>
<collection_list>
<collection>c3</collection>
</collection_list>
</element>
</catalog>

请解释一下如何在树中插入多个元素。

编辑:修复了“childElement”标签的名称。

最佳答案

您需要在内部 for 循环中添加集合,而不是外部:

for element in elementCollections:
listOfElementCollections = ['c1', 'c2', 'c3']

for elementCollection in listOfElementCollections:
childElement = etree.SubElement(element, "collection")
childElement.text = elementCollection

newtree = etree.tostring(root, encoding='utf-8')
newtree = newtree.decode("utf-8")
print newtree

关于python - 使用 lxml 将多个元素添加到 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34224854/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com