1

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?

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.