Python ElementTree:如何在非常特定的位置添加子元素? [英] Python ElementTree: How to add SubElement at VERY specific position?
问题描述
我想在XML文件中添加一个子元素,但是要放在非常特定的位置,而不是附加到末尾。
I want to add a subelement to an xml file, but in a very specific position, not appended to the end.
标准方法是:
subi = ET.SubElement(root[0][0], 'subi')
这很好。
但是:假设root [0] [0]已经有两个孩子,因此可以通过root [0] [0] [0]和root [0]访问[0] [1]。
but: Let's say, root[0][0] already has two children, hence accessible via root[0][0][0] and root[0][0][1].
我希望 subi成为新的中间孩子root [0] [0] [1],使原来的第二个孩子成为第三个孩子根[ 0] [0] [2]。
And I want "subi" to become the new middle child, root[0][0][1], making the original second child become the third child root[0][0][2].
有没有办法做到这一点? (我对生活和自然的经历会拒绝,但我对python =寄予厚望)
Is there a way to do that? (My experiences with life and nature would say no, but I have high hopes for python=)
推荐答案
您可以使用 Element.insert
方法。
You can use Element.insert
method. It allows you to specify an index.
例如,在第三个元素(索引:2)之前插入:
For example, to insert before the 3rd (index: 2) element:
>>> import xml.etree.ElementTree as ET
>>>
>>> root = ET.fromstring('''
... <root>
... <first></first>
... <second></second>
... <third></third>
... </root>
... ''')
>>>
>>> new = ET.Element('new')
>>> root.insert(2, new) # <-----------
>>> print(ET.tostring(root))
<root>
<first />
<second />
<new /><third />
</root>
这篇关于Python ElementTree:如何在非常特定的位置添加子元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!