为什么elementTree.Element.Remove()方法与直接迭代无法正确使用?

发布于 2025-01-21 22:58:42 字数 436 浏览 2 评论 0原文

我用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

明媚殇 2025-01-28 22:58:42

是的,如果您在root中使用
并且不建议使用迭代方法从其容器中删除项目。您应该为循环生成列表。

在您的第一个删除操作(使用迭代器)中,它实际上删除了所有奇数孩子(索引0、2、4,..),并将所有的孩子都留在您的根元素中。
您可以使用简单列表尝试行为:

l = [1,2,3,4,5,6]
for x in l:
    l.remove(x)
print (l)

输出

[2, 4, 6]

可以通过添加&lt; sub3&gt;元素来尝试使用XML,并观察类似的结果。

根据官方changelog 在这里方法已被弃用。

建议使用:

for child in list(root):
    # do something 

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:

l = [1,2,3,4,5,6]
for x in l:
    l.remove(x)
print (l)

It outputs

[2, 4, 6]

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:

for child in list(root):
    # do something 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文