Search code examples
pythonxmlminidom

Append child in the middle


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/>

Solution

  • You can use 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>