ElementTree XML做适当的间距和缩进

时间:2018-03-25 07:01:43

标签: python xml elementtree

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

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

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

BTW 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>

1 个答案:

答案 0 :(得分:1)

我假设您遇到的问题是打印问题。这是使用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

Where&#39; files / 49473329.xml&#39;是你的错误解析文件:

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

希望这有帮助