如何删除 etree 元素的属性?

发布于 2024-08-30 19:13:21 字数 48 浏览 5 评论 0原文

我的 etree 元素具有一些属性 - 我们如何删除特定 etree 元素的属性。

I've Element of etree having some attributes - how can we delete the attribute of perticular etree Element.

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

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

发布评论

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

评论(3

伤感在游骋 2024-09-06 19:13:21

元素对象的 .attrib 成员 包含以下字典属性 - 您可以使用 .pop("key")del 就像在任何其他字典上一样 删除键值对。

The .attrib member of the element object contains the dict of attributes - you can use .pop("key") or del like you would on any other dict to remove a key-val pair.

萌化 2024-09-06 19:13:21

当您弹出不可用的键时,您不需要try/ except。以下是您可以执行此操作的方法。

代码

import xml.etree.ElementTree as ET

tree = ET.parse(file_path)
root = tree.getroot()      

print(root.attrib)  # {'xyz': '123'}

root.attrib.pop("xyz", None)  # None is to not raise an exception if xyz does not exist

print(root.attrib)  # {}

ET.tostring(root)
'<urlset> <url> <changefreq>daily</changefreq> <loc>http://www.example.com</loc></url></urlset>'

You do not need to try/except while you are popping a key which is unavailable. Here is how you can do this.

Code

import xml.etree.ElementTree as ET

tree = ET.parse(file_path)
root = tree.getroot()      

print(root.attrib)  # {'xyz': '123'}

root.attrib.pop("xyz", None)  # None is to not raise an exception if xyz does not exist

print(root.attrib)  # {}

ET.tostring(root)
'<urlset> <url> <changefreq>daily</changefreq> <loc>http://www.example.com</loc></url></urlset>'
原野 2024-09-06 19:13:21

示例:

>>> from lxml import etree 
>>> from lxml.builder import E
>>> otree = E.div()
>>> otree.set("id","123")
>>> otree.set("data","321")
>>> etree.tostring(otree)
'<div id="123" data="321"/>'
>>> del otree.attrib["data"]
>>> etree.tostring(otree)
'<div id="123"/>'

有时要小心您没有该属性:

始终建议我们处理异常。

try:
    del myElement.attrib["myAttr"]
except KeyError:
    pass

Example :

>>> from lxml import etree 
>>> from lxml.builder import E
>>> otree = E.div()
>>> otree.set("id","123")
>>> otree.set("data","321")
>>> etree.tostring(otree)
'<div id="123" data="321"/>'
>>> del otree.attrib["data"]
>>> etree.tostring(otree)
'<div id="123"/>'

Take care sometimes you dont have the attribute:

It is always suggested that we handle exceptions.

try:
    del myElement.attrib["myAttr"]
except KeyError:
    pass
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文