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

标签 python xml elementtree

我正在尝试使用带有以下代码的 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?

最佳答案

您想要插入操作:

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

在我的测试中,这让我受益匪浅:

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

关于python - 使用 python ElementTree 库添加新的 XML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31432093/

相关文章:

python - 可以告诉 ElementTree 保留属性的顺序吗?

python - Networkx 寻找有向图的社区

python - 如何在特定条件下组合大型列表(再次列表)

xml - XPath 格式-数字带有基于变量的小数位数?

java - 如何从 Java 中的对象列表创建 XML 文件?

python - 使用 ELEMNTREE 和 Beautifulsoup 解析 XML 时遇到内存问题

python - ElementTree 命名空间不方便

python - 如何在 python 中动态获取组的组合/排列?

python - 如何让 emacs-jedi 使用项目特定的 virtualenvs

android child view 没有按下状态