我使用这段代码在原来的.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">
如何解决这个问题?
格式化输出。
from xml.dom import minidom
dom = minidom.parse('country_data.xml')
with open('dom_write.xml', 'w', encoding='UTF-8') as fh:
dom.writexml(fh, indent='', addindent='\t', newl='', encoding='UTF-8')