2
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

2
  • @MartinHonnen May I ask why you put the xpath in string() ? Commented Sep 24, 2019 at 10:12
  • Hm, I see, interesting, I never knew about that string() functionality. Thanks for explaining! :) Commented Sep 24, 2019 at 10:17

1 Answer 1

5

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]
Sign up to request clarification or add additional context in comments.

2 Comments

Is there anyway in ET that can fetch even attributes using xpath
No there isn't, unfortunately. @ is understood in predicates only (docs.python.org/3/library/…).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.