title: Inserting nodes into XML using python element tree
body: <p>I have the following XML structure and I want to add a new node if it does not exist at a specific location.</p>
  
  <pre><code>&lt;root&gt;
      &lt;OuterLevel&gt;
          &lt;Node&gt;
              &lt;Name&gt;NodeA&lt;/Name&gt;
          &lt;/Node&gt;
          &lt;Node&gt;
              &lt;Name&gt;NodeB&lt;/Name&gt;
          &lt;Node&gt;
          &lt;SpecialNode&gt;
              &lt;Name&gt;NodeZ&lt;/Name&gt;
          &lt;/SpecialNode&gt;
      &lt;/OuterLevel&gt;
   &lt;/root&gt;
  </code></pre>
  
  <p>I wrote a python script using element tree. <a href="http://docs.python.org/library/xml.etree.elementtree.html" rel="nofollow">http://docs.python.org/library/xml.etree.elementtree.html</a></p>
  
  <pre><code>import xml.etree.ElementTree as ET
  tree = ET.parse('sampleFile.xml')
  root = tree.getroot()
  newNodeStr = 'NewNode'
  
  if root[0][0].tag != newNodeStr :
      print('Now we add it')
      newNode = ET.Element(newNodeStr)
      newNodeName = ET.Element('Name')
      newNodeName.text = 'NodeC'
      newNode.append(newNodeName)
      root[0].insert(0, newNode)
  
  tree.write('sampleFileNew.xml')
  </code></pre>
  
  <p>I wanted the XML structure to look like this:</p>
  
  <pre><code>&lt;root&gt;
      &lt;OuterLevel&gt;
          &lt;NewNode&gt;
              &lt;Name&gt;NodeC&lt;/Name&gt;
          &lt;/NewNode&gt;
          &lt;Node&gt;
              &lt;Name&gt;NodeA&lt;/Name&gt;
          &lt;/Node&gt;
          &lt;Node&gt;
              &lt;Name&gt;NodeB&lt;/Name&gt;
          &lt;Node&gt;
          &lt;SpecialNode&gt;
              &lt;Name&gt;NodeZ&lt;/Name&gt;
          &lt;/SpecialNode&gt;
      &lt;/OuterLevel&gt;
   &lt;/root&gt;
  </code></pre>
  
  <p>But instead, it looks like this:</p>
  
  <pre><code>&lt;root&gt;
      &lt;OuterLevel&gt;
          &lt;NewNode&gt;&lt;Name&gt;NodeC&lt;/Name&gt;&lt;/NewNode&gt;&lt;Node&gt;
              &lt;Name&gt;NodeA&lt;/Name&gt;
          &lt;/Node&gt;
          &lt;Node&gt;
              &lt;Name&gt;NodeB&lt;/Name&gt;
          &lt;Node&gt;
          &lt;SpecialNode&gt;
              &lt;Name&gt;NodeZ&lt;/Name&gt;
          &lt;/SpecialNode&gt;
      &lt;/OuterLevel&gt;
   &lt;/root&gt;
  </code></pre>
  
  <p>I used the insert() method from element tree because I thought it would give me what I needed, which is inserting a node at a specific location. However, it looks like the insert() doesn't actually care about what is already in that position in the tree structure. Is there a method that I can use to fix the ordering? Is there a better way of doing this?</p>