import xml.etree.ElementTree as ET
tree: ET = ET.parse(file)
tree.find('.//ns1:tag/@someattribute', ns)
is resulting in {KeyError}'@', xpath expression is correct as per my knowledge, is there any way in element tree to get attribute value directly using xpath and not using .attrib
The XPath expression is syntactically OK. The problem is that find()
locates only elements. It cannot be used to find attributes.
This should work:
attr = tree.find('.//ns1:tag', ns).get('someattribute')
With lxml, you could use the xpath()
method (which returns a list):
attr = tree.xpath('.//ns1:tag/@someattribute', namespaces=ns)[0]