1
我想將一些子元素添加到xml樹的父元素中。 源XML是:使用lxml將多個元素添加到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>
請解釋一下h ow在樹中插入多個元素。編輯: 「childElement」的標籤的固定名稱
感謝您的幫助,阿里!你是對的。注意:我已經修復了childElement標籤的錯誤,所以你可以在8行代碼中修復它 – nycmoma