It's fairly well documented how to get and set the value of an attribute with LXML, but is there a way to rename the name of an existing attribute?
The goal is to get from
<element old="cheese"/>
to
<element new="cheese"/>
What I am currently doing is a bit convoluted — deleting the attribute and then re-adding it with a new name and the old value:
from io import StringIO
from lxml import etree
doc = StringIO('<element old="cheese"/>')
tree = etree.parse(doc)
elem = tree.getroot()
attr_value = elem.attrib['old']
del elem.attrib['old']
elem.attrib['new'] = attr_value
Is there a way to rename an attribute directly instead of deleting and re-adding with a new key?
CodePudding user response:
First I wish I could upvote your question twice because you gave a minimal, reproducible example that I could copy/paste/run. Those new to stack overflow should take note! I suppose it's because users that have been around as long as you and I don't ask as many questions.
I don't think what you're doing is that convoluted, but since .attrib
is a dict you could do something like this instead:
elem.attrib['new'] = elem.attrib.pop('old')
Full example:
from io import StringIO
from lxml import etree
doc = StringIO('<element old="cheese"/>')
tree = etree.parse(doc)
elem = tree.getroot()
elem.attrib['new'] = elem.attrib.pop('old')
print(etree.tostring(tree).decode())
Printed output...
<element new="cheese"/>