how to remove attribute of a etree Element?

2019-03-14 07:31发布

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

3条回答
我欲成王,谁敢阻挡
2楼-- · 2019-03-14 08:00

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.

查看更多
Bombasti
3楼-- · 2019-03-14 08:17

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
查看更多
你好瞎i
4楼-- · 2019-03-14 08:26

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>'
查看更多
登录 后发表回答