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

时间:2015-12-11 13:38:29

标签: python xml lxml

我想将一些子元素添加到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>

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

编辑: 固定&#34; childElement&#34;。

的标签名称

2 个答案:

答案 0 :(得分:1)

您需要在内部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

答案 1 :(得分:0)

使用此代码:

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, "collectionName")
    listOfElementCollections = ['c1', 'c2', 'c3']

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

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

您需要在循环中创建新元素。