Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python xml.etree-删除节点但保留子节点(将子节点分配给祖父母)_Python_Xml_Xml Parsing - Fatal编程技术网

python xml.etree-删除节点但保留子节点(将子节点分配给祖父母)

python xml.etree-删除节点但保留子节点(将子节点分配给祖父母),python,xml,xml-parsing,Python,Xml,Xml Parsing,在Python中,如何使用xml.etreeAPI删除节点但保留其子节点 是的,我知道有一个问题,但由于xml.etree是Python网站的一部分,我认为它也应该得到一个答案 原始xml文件: <?xml version="1.0"?> <data> <country name="Liechtenstein"> <rank>1</rank> <year>2008</year&g

在Python中,如何使用
xml.etree
API删除节点但保留其子节点

是的,我知道有一个问题,但由于
xml.etree
是Python网站的一部分,我认为它也应该得到一个答案

原始xml文件:

<?xml version="1.0"?>
<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="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>
我的打印语句的输出:

data
     country
         rank
         gdppc
         neighbor
     country
         rank
         gdppc
     country
         rank
         gdppc
         neighbor
我们马上可以看到有一个问题:
国家
缺少标签
年份
和一些
邻居
标签

生成的
.xml
输出:

<data>
    <rank>1</rank>
        <gdppc>141100</gdppc>
        <neighbor direction="W" name="Switzerland" />
    <rank>4</rank>
        <gdppc>59900</gdppc>
        <rank>68</rank>
        <gdppc>13600</gdppc>
        <neighbor direction="E" name="Colombia" />
    </data>

1.
141100
4.
59900
68
13600
这显然是错误的

问题:为什么会发生这种情况


我可以想象这是从添加/删除列表中破坏了某些内容,即我已经“无效”了类似于迭代器的列表。

从程序中删除这一行:

        country.remove(country_child)

xml.etree.ElementTree.Element
的迭代本质上是传递给子元素的
列表。在迭代过程中修改该列表将产生奇怪的结果。

为什么这条线会破坏东西?我现在正在检查。我相信这是因为你猜测的原因,你在对列表进行迭代时正在修改它。但它是元素的
列表
,不是迭代器,对吗?我之所以在这里有这行代码是为了最小化内存使用。如果我删除该行,我将临时添加sizeof(国家的儿童)。我认为您不会添加任何内存
country\u parent.append()
不会创建新的
元素
,它只会在现有元素中链接。
对于country[:]中的country\u child:
,根据您上一个问题中链接到的答案,
        country.remove(country_child)