如何将元素插入一组相似的元素

时间:2019-05-20 14:55:21

标签: python-3.x lxml

我有一个包含一组相似元素的XML,我需要在该组中间插入元素

例如:

XML = """
<first>
<second>second element</second>
<third>third element</third>
<third>another third element</third>
<third>yet another third element</third>
</first>
"""

我需要能够在第三个元素的中间插入另一个元素。

我尝试使用findall:

from lxml import etree

parser = etree.XMLParser()
root = etree.fromstring(XML, parser)

newElement = etree.Element('third')
newElement.text = 'new element added'

elementList = root.findall('third')
elementList.insert(2, newElement)

print(etree.tostring(root))

输出:

<first>
<second>second element</second>
<third>third element</third>
<third>another third element</third>
<third>yet another third element</third>
</first>

我要完成的工作:

<first>
<second>second element</second>
<third>third element</third>
<third>another third element</third>
<third>new element added</third>
<third>yet another third element</third>
</first>

我认为我可以使用root.insert(<place>, <element>),但是我尝试更改的实际XML更大(太大而无法发布),并且不确定这是否是最Python化的方式。

任何帮助将不胜感激。谢谢

1 个答案:

答案 0 :(得分:0)

这可能是您想要的:

xml = etree.fromstring(XML)

for item in xml.xpath('.'):
   newElement = etree.Element('third')  
   newElement.text = "new element added"
   nav = item.findall('third')  
   item.insert(item.index(nav[2]), newElement) 

etree.tostring(xml).decode().replace('\n','')

输出:

<first>
<second>second element</second>
<third>third element</third>
<third>another third element</third>
<third>new element added</third>
<third>yet another third element</third>
</first>