Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove an attribute from an ElementTree Element?

I have a simple XML object <person> created with xml.etree.ElementTree.

<person name='John' age='21' />

I want to modify the XML element to remove the age attribute.

<person name='John' />

I can access the attribute using .get("age"), but using .remove("age") results in a TypeError.

import xml.etree.ElementTree as ElementTree

xml = ElementTree.Element('person', name="john", age="21")
xml.remove("age") 
# TypeError: remove() argument must be xml.etree.ElementTree.Element, not str

According to the documentation, .remove() can only be used to remove subelements. There doesn't seem to be any alternative option for removing attributes.

How can I remove an XML attribute from an xml.etree.ElementTree object?

like image 630
Stevoisiak Avatar asked May 11 '26 22:05

Stevoisiak


2 Answers

You can try del xml.attrib["age"]

import xml.etree.ElementTree as ElementTree

xml = ElementTree.Element('person', Name="john", age="21")
print(xml.items())
del xml.attrib["age"]
print(xml.items())

Will produce:

[('Name', 'john'), ('age', '21')]
[('Name', 'john')]
like image 175
Adrien Logut Avatar answered May 13 '26 13:05

Adrien Logut


Use xml.attrib.pop("age").

from xml.etree import ElementTree

xml = ElementTree.Element('person', name="john", age="21")
print(ElementTree.tostring(xml).decode())

xml.attrib.pop("age")
print(ElementTree.tostring(xml).decode())

Output:

<person name='John' age='21' />
<person name='John' />

Explanation:

The attrib member of ElementTree is implemented as a dict object, meaning you can use any standard dictionary methods on it.

like image 43
Stevoisiak Avatar answered May 13 '26 13:05

Stevoisiak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!