【发布时间】:2020-09-15 16:20:45
【问题描述】:
我使用此代码在原始 .xml(取自 ElementTree 文档的文件)中插入一个新节点:
import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()
my_xml = """
<country name="Togo">
<rank updated="yes">2</rank>
<year>2000</year>
<gdppc>3</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
"""
new_contry = ET.fromstring(my_xml)
root.insert(1,new_contry)
tree.write('essai_insert_output.xml')
root = tree.getroot()
但是结果破坏了新节点和下一个节点之间的正确缩进:
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E" />
<neighbor name="Switzerland" direction="W" />
</country>
<country name="Togo">
<rank updated="yes">2</rank>
<year>2000</year>
<gdppc>3</gdppc>
<neighbor name="Austria" direction="E" />
<neighbor name="Switzerland" direction="W" />
</country><country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N" />
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W" />
<neighbor name="Colombia" direction="E" />
</country>
</data>
新节点<country name="Togo">放置得很好,但在它的最后,我们有这个冲突:
</country><country name="Singapore">
如何治疗这种影响?
【问题讨论】:
-
只是格式问题。结构是对的。
-
@dabingsou 好的,但是如何改进格式?我必须为某人转换 XML 文件,重点是提供格式良好的 XML 输出(我尝试了 lxml 模块,但遇到了同样的问题)。
-
这里是一个格式化输出的例子。
-
您可以通过在
new_contry元素的tail中添加一些空格来使输出看起来更漂亮。像这样:new_contry.tail = "\n ". -
以下是使用 lxml 获得漂亮打印输出的方法:stackoverflow.com/q/42577999/407651
标签: python insert indentation elementtree pretty-print