Skip to main content
 首页 » 编程设计

python之ElementTree XML 做适当的间距和缩进

2025年01月19日8shangdawei

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

<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”是您错误解析的文件:

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

希望对你有帮助