【问题标题】:python element tree insert is adding children twice at required position and at the endpython元素树插入在所需位置和最后添加两次子项
【发布时间】: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


    【解决方案1】:

    您的代码实际上添加了两次:

    1. newnode = et.SubElement(firstcountrynode,"Capital")
    2. 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-13
      • 1970-01-01
      • 2020-04-04
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多