7

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.

2
  • What have you tried so far? What's your concrete problem? What's the error message? Or do you expect us to write your code? Commented Oct 5, 2012 at 22:36
  • The definition of my problem is very concise. I did read the doc (and admitingly missed the proper answer on the first time through) - I hadn't coded anything yet because I hadn't found anything in the docs which suited my needs. stackoverflow.com/questions/4739834/… When you asked that question, did you expect someone to write your code? What was your error message? Commented Oct 6, 2012 at 0:05

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you - that looks exactly like what I was looking for. I'm used to perl parsers which use copy/paste and didn't think to look for an insert method. I'll give it a shot when I'm back at work on Monday and upvote/accept.
On my Python 2.7 runtime, insert replaces the existing component at that position. In this example, childA would be replaced by newChild

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.