I've Element of etree having some attributes - how can we delete the attribute of perticular etree Element.
Asked
Active
Viewed 4.3k times
3 Answers
50
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.

Amber
- 507,862
- 82
- 626
- 550
-
5I found 1 another solution etree.strip_attrbutes(element,'attribute_name')) – shahjapan Apr 27 '10 at 12:37
-
2While `pop` works, `del` does not: `AttributeError: attribute 'attrib' of 'lxml.etree._Element' objects is not writable` - see also the [Element](http://docs.python.org/library/xml.etree.elementtree.html#element-objects) documentation which speaks of a dict like interface, but also does not mention `pop`. – blueyed Jan 31 '11 at 13:28
-
3@shahjapan etree.strip_attrbutes is not safe because it will Delete all attributes with the provided attribute names from an Element (or ElementTree) and its descendants. http://lxml.de/api/lxml.etree-module.html#strip_attributes – Divyesh Patel Jan 19 '15 at 12:34
-
The documentation says `Note that while the attrib value is always a real mutable Python dictionary, an ElementTree implementation may choose to use another internal representation, and create the dictionary only if someone asks for it. To take advantage of such implementations, use the dictionary methods below whenever possible.` (see https://docs.python.org/3/library/xml.etree.elementtree.html#module-xml.etree.ElementTree). Isn't this solution breaking that recommendation? – David Faure Nov 28 '20 at 09:38
13
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>'

A.J.
- 8,557
- 11
- 61
- 89
10
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

macm
- 1,959
- 23
- 25
-
5It is somewhat better to only catch the expected exceptions in case something else went wrong. In this case: except KeyError: – dabhand Oct 02 '15 at 13:41