ElementTree删除元素

编程入门 行业动态 更新时间:2024-10-26 17:34:31
本文介绍了ElementTree删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

Python noob在这里。想知道什么是删除所有带有已更新的 个人资料标签的最佳方法。属性值 true 。

Python noob here. Wondering what's the cleanest and best way to remove all the "profile" tags with updated attribute value of true.

我尝试了以下代码,但是抛出了它: SyntaxError(不能在元素上使用绝对路径)

I have tried the following code but it's throwing: SyntaxError("cannot use absolute path on element")

root.remove(root.findall("//Profile[@updated='true']"))

XML:

<parent> <child type="First"> <profile updated="true"> <other> </other> </profile> </child> <child type="Second"> <profile updated="true"> <other> </other> </profile> </child> <child type="Third"> <profile> <other> </other> </profile> </child> </parent>

推荐答案

如果使用的是 xml .etree.ElementTree ,则应使用 remove() 方法来删除节点,但这需要您具有父节点引用。因此,解决方案为:

If you are using xml.etree.ElementTree, you should use remove() method to remove a node, but this requires you to have the parent node reference. Hence, the solution:

import xml.etree.ElementTree as ET data = """ <parent> <child type="First"> <profile updated="true"> <other> </other> </profile> </child> <child type="Second"> <profile updated="true"> <other> </other> </profile> </child> <child type="Third"> <profile> <other> </other> </profile> </child> </parent>""" root = ET.fromstring(data) for child in root.findall("child"): for profile in child.findall(".//profile[@updated='true']"): child.remove(profile) print(ET.tostring(root))

打印:

<parent> <child type="First"> </child> <child type="Second"> </child> <child type="Third"> <profile> <other> </other> </profile> </child> </parent>

请注意,使用 lxml .etree 这会更简单:

root = ET.fromstring(data) for profile in root.xpath(".//child/profile[@updated='true']"): profile.getparent().remove(profile)

其中 ET import lxml.etree as ET

更多推荐

ElementTree删除元素

本文发布于:2023-11-30 11:09:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649759.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   ElementTree

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!