Python:LXML - 如何将元素添加到现有元素树

时间:2018-04-19 09:53:52

标签: python xml lxml elementtree

我需要通过向现有元素添加子元素来修改现有的xml文件。我使用lxml库。

<addressbook>
<person>
    <name>Eric Idle</name>
    <phone type='fix'>999-999-999</phone>
    <phone type='mobile'>555-555-555</phone>
    <address>
        <street>12, spam road</street>
        <city>London</city>
        <zip>H4B 1X3</zip>
    </address>
</person>
</addressbook>

这是XML;让我们想要添加第二个名字:

<addressbook>
<person>
    <name>Eric Idle</name>
    <name>TEST TEST</name>
    <phone type='fix'>999-999-999</phone>
    <phone type='mobile'>555-555-555</phone>
    <address>
        <street>12, spam road</street>
        <city>London</city>
        <zip>H4B 1X3</zip>
    </address>
</person>
</addressbook>

我知道我可以解析文件并使用etree.getroot()获取根目录但是我可以将/ adressbook / person作为etree.element吗?

1 个答案:

答案 0 :(得分:2)

您可以使用xpath来定位所有感兴趣的<name>元素,然后附加一个兄弟元素:

from lxml import etree

data = r'''
<addressbook>
<person>
    <name>Eric Idle</name>
    <phone type='fix'>999-999-999</phone>
    <phone type='mobile'>555-555-555</phone>
    <address>
        <street>12, spam road</street>
        <city>London</city>
        <zip>H4B 1X3</zip>
    </address>
</person>
<person>
    <name>Eric Idle</name>
    <phone type='fix'>999-999-999</phone>
    <phone type='mobile'>555-555-555</phone>
    <address>
        <street>12, spam road</street>
        <city>London</city>
        <zip>H4B 1X3</zip>
    </address>
</person>
</addressbook>
'''

doc = etree.fromstring(data)

#process the first <name> element of every person in addressbook
for name in doc.xpath('/addressbook/person/name[1]'):
    parent = name.getparent()
    parent.insert(parent.index(name)+1, etree.XML('<name>TEST TEST</name>'))

print(etree.tostring(doc))