小编thi*_*lex的帖子

使用 python xml.etree 模块格式化插入的元素,以包含新行

我将单个元素插入到一个大的 xml 文件中。我希望插入的元素位于顶部(所以我需要使用 root.insert 方法,而不能只是附加到文件中)。我还希望元素的格式与文件的其余部分相匹配。

原始 XML 文件的格式为

<a>
    <b>
        <c/>
    </b>
    <d>
        <e/>
    </d>
    ....
</a>
Run Code Online (Sandbox Code Playgroud)

然后我运行以下代码:

import xml.etree.ElementTree as ET    

xmlfile = ET.parse('file.xml')
a = xmlfile.getroot()

f = ET.Element('f')
g = ET.SubElement(f,'g')

a.insert(1, f)

xmlfile.write('file.xml')
Run Code Online (Sandbox Code Playgroud)

它以以下形式创建输出:

<a>
    <b>
        <c/>
    </b>
    <f><g/></f><d>
        <e/>
    </d>
    ....
</a>
Run Code Online (Sandbox Code Playgroud)

但我想要它的形式:

<a>
    <b>
        <c/>
    </b>
    <f>
        <g/>
    </f>
    <d>
        <e/>
    </d>
    ....
</a>
Run Code Online (Sandbox Code Playgroud)

使用 Jonathan Eunice 的解决方案“如何让 Python 的 ElementTree 漂亮地打印到 XML 文件?” 我添加了以下代码来替换 xmlfile.write 命令:

from xml.dom import minidom
xmlstr = minidom.parseString(ET.tostring(a)).toprettyxml(indent=" …
Run Code Online (Sandbox Code Playgroud)

python xml pretty-print elementtree xml.etree

5
推荐指数
1
解决办法
5860
查看次数

标签 统计

elementtree ×1

pretty-print ×1

python ×1

xml ×1

xml.etree ×1