奇怪的ElementTree remove()行为

时间:2015-02-26 09:07:12

标签: python python-2.6

我在尝试删除元素时使用elementTree这是一个奇怪的问题, 它似乎只是导航和删除奇数元素。

这是代码

import xml.etree.ElementTree as ET

tree = ET.parse('bug_remove.xml')
root = tree.getroot()

for element in root:
    print element.tag

print "remove all"

for element in root:
    print "remove element : "+element.tag
    root.remove(element)

print "remaining elements"

for element in root:
    print element.tag

输出:

element1
element2
element3
element4
element5
element6
=> remove all
remove element : element1
remove element : element3
remove element : element5
=> remaining elements
element2
element4
element6

解析了xml文件:

<root>
        <element1>
        </element1>
        <element2>
        </element2>
        <element3>
        </element3>
        <element4>
        </element4>
        <element5>
        </element5>
        <element6>
        </element6>
</root>

1 个答案:

答案 0 :(得分:0)

好吧,因为在迭代同一个列表时删除一个元素会产生问题, 修复是遍历副本(root [:]):

import xml.etree.ElementTree as ET

tree = ET.parse('bug_remove.xml')
root = tree.getroot()

print "XML length : ", len(root)

for element in root[:]:
    print "remove element : "+element.tag
    root.remove(element)

print "remaining elements"

for element in root:
    print element.tag

输出:

 XML length :  6
 remove element : element1
 remove element : element2
 remove element : element3
 remove element : element4
 remove element : element5
 remove element : element6
 remaining elements

可以帮助有相同问题的人