Reputation: 369
I am having an issue with the command find and it is not working. However, in theory it should be working.
Let's say that I have this xml file:
<?xml version="1.0">
<pxml name="es">
things here
</pxml
I want to find the element pxml to add there an attribute. So I am using this code:
from lxml import etree as et
lang = 'de'
tree = et.parse("file.xml")
root = tree.getroot()
txml_element = root.find('//pxml')
txml_element.attrib['language'] = lang
I get the following error message:
SyntaxError: cannout use absolute path on element
Also, if i don't do the tree.getroot and I use the find in the tree I always a None element. What do I am missing?
I don't understand why am I getting this message error. Also if use only root.find('pxml') it returns None.
However, using xpath I get a list of the elements, it works:
lang = 'de'
tree = et.parse("file.xml")
root = tree.getroot()
txml_elements = root.xpath('//pxml')
for element in txml_elements:
element.attrib['language'] = lang
print(element.attrib)
#print (et.tostring(tree))
Upvotes: 1
Views: 2438
Reputation: 383
Try to use dot:
root.find('.')
If you need only pxml element, check for tag
txml_element.tag
Upvotes: 1