在 etree 上使用 iterdescendants() 时,可以修改树吗?

发布于 2024-11-28 08:12:34 字数 569 浏览 1 评论 0原文

(Python 3.2)

我正在使用 etree 来解析一些 XML。为此,我使用 iterdescendants() 递归地迭代文档。所以,就像:

for elem in doc.iterdescendants():
    if elem.tag == "tag":
        pass # Further processing

有时,我处理一个父标签,其中包含我想防止在以后的递归中处理的子标签。毁掉孩子可以吗?

在我的初始测试中,我尝试过:

for child in elem.getchildren(): child.clear()

出于某种原因,这会导致紧随 elem 之后的元素被处理。就像元素也被删除一样。

然后我尝试了这个,它有效(因为它删除了父级及其子级,但不会导致父级的任何后续兄弟姐妹被跳过/受影响):

elem.clear()

任何人都可以对此有所了解吗?谢谢,

(Python 3.2)

I'm using etree to parse some XML. To do this, I'm recursively iterating through the document with iterdescendants(). So, something like:

for elem in doc.iterdescendants():
    if elem.tag == "tag":
        pass # Further processing

Sometimes, I process a parent tag that contains children that I want to prevent from being processed in a later recursion. Is it ok to destroy the children?

In my initial testing, I've tried:

for child in elem.getchildren(): child.clear()

For some reason, this results in the element immediately after elem from being processed. It's like the element gets removed as well.

I then tried this, which works (in that it removes the parent and its children, but doesn't result in any subsequent siblings of the parent from being skipped/affected as well):

elem.clear()

Can anyone shed some light on this? Thanks,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

爱给你人给你 2024-12-05 08:12:34

我用以下代码代替了您的代码,它似乎可以工作,删除所有子元素。我使用 iterfind 查找带有该标签的所有后代并将其删除。

for element in doc.iterfind('.//%s'%tag):
    element.getparent().remove(element)

I have the following code in place of yours and it seems to work, deleting all the child elements. I use iterfind to find all descendants with the tag and delete them.

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