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

How can I insert elements into a group of like elements

我有一个 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 更大(对于 post 来说太大了)并且不确定那是否会是最 Pythonic 的方式。

如有任何帮助,我们将不胜感激。谢谢

这可能是您想要的:

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>