【问题标题】:ElementTree XML to do proper spacing and indentationElementTree XML 做适当的间距和缩进
【发布时间】:2018-03-25 07:01:42
【问题描述】:

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

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

【问题讨论】:

标签: python xml elementtree


【解决方案1】:

我假设您面临的问题是打印问题。这是一个使用 minidom 模块的代码 sn-p,它会自动以所需的格式解析您的 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>

希望对你有帮助

【讨论】:

  • 但这看起来也没有正确间隔,结束数据标签应该在下一行,并且该元素没有缩进。
  • @shinzou 你能添加你得到的输出吗?
  • i.imgur.com/ahcRiaV.png 我看你是想美化它,但看起来它在每一行之前和之后都添加了一个换行符,这不是我想要的。
  • @shinzou 这是 minidom 的一个已知问题,一旦你得到解析的 XML 字符串,你可以去掉任何不需要的换行符
  • 呃这么多逻辑...为什么这么基本的东西不是minidom或elementree的一部分?我确定我不是第一个遇到这个问题的人。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-13
  • 1970-01-01
  • 2020-09-15
  • 2011-05-30
  • 1970-01-01
相关资源
最近更新 更多