Python ElementTree: How to add SubElement at VERY specific position?

十年热恋 提交于 2019-12-10 21:44:38

问题


I want to add a subelement to an xml file, but in a very specific position, not appended to the end.

The standard way is:

subi = ET.SubElement(root[0][0], 'subi')

which is fine.

but: Let's say, root[0][0] already has two children, hence accessible via root[0][0][0] and root[0][0][1].

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].

Is there a way to do that? (My experiences with life and nature would say no, but I have high hopes for python=)


回答1:


You can use Element.insert method. It allows you to specify an index.

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>


来源:https://stackoverflow.com/questions/25824920/python-elementtree-how-to-add-subelement-at-very-specific-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!