ElementTree XML 做适当的间距和缩进

ElementTree XML to do proper spacing and indentation

如果我有这样的文件,例如:

<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor direction="E" name="Austria" />
        <neighbor direction="W" name="Switzerland" />
    </country>
</data>

如果我附加一个元素:

newTagContentString = """
<usertype id="99999">
    <role name="admin" />
</usertype>"""
c.append(newXMLElement)

缩进不正确:

<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor direction="E" name="Austria" />
        <neighbor direction="W" name="Switzerland" />
    </country>
<usertype id="99999">
    <role name="admin" />
</usertype></data>

有没有办法让它正确缩进?

顺便说一句 c.insert(0, newXMLElement) 也没有保持很好的间距:

<data>
    <usertype id="99999">
    <role name="admin" />
</usertype><country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor direction="E" name="Austria" />
        <neighbor direction="W" name="Switzerland" />
    </country>
</data>

我假设您遇到的问题是打印问题。这是使用 minidom 模块的代码片段,它会自动以所需格式解析您的 xml:

import xml.etree.ElementTree as ET
import xml.dom.minidom

parent_file_path = 'files/49473329.xml'
parent_tree = ET.parse(parent_file_path)
parent = parent_tree.getroot()
xmlstr = xml.dom.minidom.parseString(ET.tostring(parent)).toprettyxml()
print xmlstr

其中 'files/49473329.xml' 是您的 mis-parsed 文件:

<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor direction="E" name="Austria" />
        <neighbor direction="W" name="Switzerland" />
    </country>
<usertype id="99999">
    <role name="admin" />
</usertype></data>

希望对您有所帮助