Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert xml element as first child using ElementTree in python

I'm using python to create an element in an xml document and then insert it as the FIRST CHILD of the document. So, if I were creating an elment named newChild I would want xml like this...

<root>
  <childA></childA>
  <childB></childB>
  <childC></childC>
</root>

to become...

<root>
  <newChild></newChild>
  <childA></childA>
  <childB></childB>
  <childC></childC>
</root>

I know that the order of elements in arbitrary xml shouldn't matter, but I writing xml doc for an ancient system which breaks if xml elements aren't in the expected order, so I don't have a choice in that regard.

like image 901
Dave Avatar asked Oct 05 '12 22:10

Dave


1 Answers

The xml.etree.ElementTree.Element.insert method allows you to add a new sub-element to an element inserted at a specific position.

In your case element.insert(0, new_sub_element) should do the trick.

like image 198
Pedro Romano Avatar answered Sep 23 '22 05:09

Pedro Romano