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, 'subi')
which is fine.
but: Let's say, root already has two children, hence accessible via root and root.
And I want "subi" to become the new middle child, root, making the original second child become the third child root.
Is there a way to do that? (My experiences with life and nature would say no, but I have high hopes for python=)
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>