【发布时间】: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>
【问题讨论】:
-
以前也有人问过类似的问题。例如:stackoverflow.com/questions/28813876/…。如果可以使用 lxml 代替 ElementTree,那么漂亮的打印会更容易。
标签: python xml elementtree