I have the following XML structure and I want to add a new node if it does not exist at a specific location.
<root>
<OuterLevel>
<Node>
<Name>NodeA</Name>
</Node>
<Node>
<Name>NodeB</Name>
<Node>
<SpecialNode>
<Name>NodeZ</Name>
</SpecialNode>
</OuterLevel>
</root>
I wrote a python script using element tree. http://docs.python.org/library/xml.etree.elementtree.html
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')
I wanted the XML structure to look like this:
<root>
<OuterLevel>
<NewNode>
<Name>NodeC</Name>
</NewNode>
<Node>
<Name>NodeA</Name>
</Node>
<Node>
<Name>NodeB</Name>
<Node>
<SpecialNode>
<Name>NodeZ</Name>
</SpecialNode>
</OuterLevel>
</root>
But instead, it looks like this:
<root>
<OuterLevel>
<NewNode><Name>NodeC</Name></NewNode><Node>
<Name>NodeA</Name>
</Node>
<Node>
<Name>NodeB</Name>
<Node>
<SpecialNode>
<Name>NodeZ</Name>
</SpecialNode>
</OuterLevel>
</root>
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?