2

I've installed the ElementTree library from here: http://effbot.org/zone/element.htm in python 2.7.

I've parsed in an xml file:

tree_a=parse('/home/user/cookies.xml')

The question that emerges now, and where I coudln't extract the information from the documentation of effbot ElementTree:

How can I access a node from the xml-tree via calling it by its attribute value?

something like

tree_a.getNode(my_attribute,my_attribute_value)

in an example:

tree_a.getNode(cookie_diameter, 12)

so that query would return the node from the xml-tree, that has as 'cookie_diameter' attribute the value 12

Does a built-in function exist ?

Best regards

Daniyal

1
  • 1
    @poke mentions it. I'd like to repeat ElementTree is a part of Python stdlib since Python 2.5. Commented Nov 5, 2011 at 23:08

1 Answer 1

5

ElementTree has a limited support for XPath. While it does not support everything, some more advanced things work. You can query for attribute values with ElementTree 1.3+ (built-in in Python 2.7+ and Python 3.2+) like this:

tree.find( './/*[@cookie_diameter="12"]' )

For the full XPath support see the documentation on effbot.org.

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent answer. I see nothing to add.

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.