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?
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')]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With