Append child in the middle
Question: I would like to add an element to an XML file using minidom from python. Let's
assume i have the following xml file

    
    
    <node-a>
        <node-1/>
        <node-2/>
        <node-3/>
    <node-a/>
    

in this case i can easily append an element "node-4" as follow

    
    
    node4 = designDOM.createElement('node-4')
    nodea.appendChild(node4)
    

resulting with the following xml:

    
    
    <node-a>
        <node-1/>
        <node-2/>
        <node-3/>
        <node-4/>
    <node-a/>
    

my questrion is: if I would like to force the insertion of an element in a
specific position instead of in the end... what should i do? for instance if i
want an element "2-a" as in the following xml what shold i do?

    
    
    <node-a>
        <node-1/>
        <node-2/>
        <node-2a/>
        <node-3/>
        <node-4/>
    <node-a/>
    


Answer: You can use
[`insertBefore()`](https://docs.python.org/2.7/library/xml.dom.html#xml.dom.Node.insertBefore):

    
    
    import xml.dom.minidom
    
    data = """<node-a>
        <node-1/>
        <node-2/>
        <node-3/>
    </node-a>"""
    
    dom = xml.dom.minidom.parseString(data)
    node_a = dom.getElementsByTagName('node-a')[0]
    
    node_4 = dom.createElement('node-4')
    node_a.appendChild(node_4)
    
    node_3 = dom.getElementsByTagName('node-3')[0]
    node2_a = dom.createElement('node-2a')
    node_a.insertBefore(node2_a, node_3)
    
    print dom.toprettyxml()
    

prints:

    
    
    <node-a>
        <node-1/>
        <node-2/>
        <node-2a/>
        <node-3/>
        <node-4/>
    </node-a>
    

