使用 python ElementTree 库添加新的 XML 元素

Adding a new XML element using python ElementTree library

我正在尝试使用带有以下代码的 python ElementTree 库向 xml 文件添加新元素。

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)

我要它呈现的XML格式如下

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

但是 xml 它实际呈现的格式不正确

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

我应该如何更改我的代码才能呈现正确的 xml?

您想要insert操作:

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

在我的测试中得到了我:

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