我需要通过向现有元素添加子元素来修改现有的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吗?
答案 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))