Zee
Zee

Reputation: 1420

Adding a new XML element using python ElementTree library

I'm trying to add a new element to an xml file using the python ElementTree library with the following code.

from xml.etree import ElementTree as et
def UpdateXML(pre):
    xml_file = place/file.xml
    tree = et.parse(xml_file)
    root = tree.getroot()
    for parent in root.findall('Parent'):
        et.SubElement(parent,"NewNode", attribute=pre)
    tree.write(xml_file)

The XML I want it to render is in the following format

<Parent>
            <Child1 Attribute="Stuff"/>
            <NewNode Attribute="MoreStuff"/> <--- new
            <Child3>
            <Child4>
            <CHild5>
            <Child6> 
    </Parent>

However the xml it actually renders is in this incorrect format

<Parent>
                <Child1 Attribute="Stuff"/>
                <Child3>
                <Child4>
                <CHild5>
                <Child6>
                <NewNode Attribute="MoreStuff"/> <--- new 
        </Parent>

What do I change in my code to render the correct xml?

Upvotes: 1

Views: 1154

Answers (1)

larsks
larsks

Reputation: 312650

You want the insert operation:

node = et.Element('NewNode')
parent.insert(1,node)

Which in my testing gets me:

<Parent>
            <Child1 Attribute="Stuff" />
            <NewNode /><Child3 />
            <Child4 />
            <CHild5 />
            <Child6 /> 
    </Parent>

Upvotes: 2

Related Questions