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

thi*_*lex 5 python xml pretty-print elementtree 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="   ")
with open("New_Database.xml", "w") as f:
    f.write(xmlstr)
Run Code Online (Sandbox Code Playgroud)

但是,整个文件的格式仍然不正确。它正确格式化了新元素,但原始元素现在被隔开:

<b>


    <c/>


</b>


<f>
    <g/>
</f>
<c>


    <d/>


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

我认为这是因为 toprettyxml() 命令在 '\n' 分隔符处添加了一个新行(因此在当前格式中添加了 2 个新行)。摆弄输入只会改变添加的元素或原始元素的格式是否不正确。我需要一种方法在添加新元素之前修改新元素或原始元素,以便它们的格式相同,然后我可以在打印前重新格式化整个批次?是否可以使用“xml.etree.ElementTree”添加格式?

提前致谢。

mzj*_*zjn 4

可以使用texttail属性来修改空白。也许这对你来说已经足够好了。请参阅下面的演示。

输入文件:

<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')

f.tail = "\n    "
f.text = "\n        "
g.tail = "\n    "

a.insert(1, f)

print ET.tostring(a)
Run Code Online (Sandbox Code Playgroud)

输出:

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