我想在几个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")
与testdata.xml从python文档示例
<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>
欢迎提出任何建议。谢谢。
您的代码实际上添加了两次:
newnode = et.SubElement(firstcountrynode,"Capital")
firstcountrynode.insert(2,newnode)
请参阅下面的代码,它只添加一次
import xml.etree.ElementTree as ET
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>'''
root = ET.fromstring(xml)
first_country = root.find('country')
capital = ET.SubElement(first_country,'capital')
capital.text = 'Vaduz'
ET.dump(root)