gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:46:23 25 4
gpt4 key购买 nike

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

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

希望对你有帮助

关于python - ElementTree XML 做适当的间距和缩进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49473329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com