为什么elementTree.Element.Remove()方法与直接迭代无法正确使用?
我用Python XML.Etree.ElementTree编辑XML文件。 这是简单的文件示例:
<root>
<sub1>1</sub1>
<sub2>2</sub2>
</root>
我想删除所有根子元素。当我使用
...
for child in root:
root.remove(child)
...
“删除”方法时,仅删除第一个子元素。但是
...
for child in root.getchildren():
root.remove(child)
...
它可以与所有子元素一起使用。为什么会发生这种情况?是某些迭代器功能,还是我需要更多地了解“删除”方法?
I`m editing a XML file with Python xml.etree.ElementTree.
Here is simple file example:
<root>
<sub1>1</sub1>
<sub2>2</sub2>
</root>
And I want to remove all root subelements. When I use
...
for child in root:
root.remove(child)
...
'remove' method deletes only first subelement. But with
...
for child in root.getchildren():
root.remove(child)
...
it works with all subelements. Why is this happening? Is it some iterator feature, or I need to know more about 'remove' method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,如果您在root中使用
为
并且不建议使用迭代方法从其容器中删除项目。您应该为循环生成列表。
在您的第一个删除操作(使用迭代器)中,它实际上删除了所有奇数孩子(索引0、2、4,..),并将所有的孩子都留在您的根元素中。
您可以使用简单列表尝试行为:
输出
可以通过添加
&lt; sub3&gt;
元素来尝试使用XML,并观察类似的结果。根据官方changelog 在这里方法已被弃用。
建议使用:
Yes, it is an iterator if you use
for child in root:
And it is not recommended to remove item from its container using the iterator method. You should generate a list for your loop.
In your first remove operation (using an iterator), it actually remove all odd children (index 0, 2, 4, ..) and leave all even children in your root element.
You can try the behaviour using a simple list:
It outputs
You can try it with your XML by adding a
<sub3>
element, and observe the similar result.According to the official changelog here, the
getchildren
method is already deprecated.It is suggested to use: