【发布时间】:2021-12-01 00:22:38
【问题描述】:
我想在几个 xml 文件中为每个节点添加一些字段。但是,我的脚本将子元素添加了两次,它们应该去的地方和父元素的末尾。
我试图简化问题,只在第一个节点插入一个字段,但我仍然重现了这个问题。这是程序:
tree = et.parse("testdata.xml")
root = tree.getroot()
firstcountrynode= root.find("country")
newnode = et.SubElement(firstcountrynode,"Capital")
newnode.text = "Vaduz"
firstcountrynode.insert(2,newnode)
tree.write("testresult.xml")
使用 python 文档示例中的 testdata.xml
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
</data>
我得到:
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2008</year>
<Capital>Vaduz</Capital><gdppc>141100</gdppc>
<neighbor name="Austria" direction="E" />
<neighbor name="Switzerland" direction="W" />
<Capital>Vaduz</Capital></country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N" />
</country>
</data>
欢迎提出任何建议。谢谢。
【问题讨论】:
标签: python xml insert parent-child elementtree