Daniyal
Daniyal

Reputation: 905

Python - ElementTree Library - Search through tree by attribute value

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

Upvotes: 2

Views: 1239

Answers (1)

poke
poke

Reputation: 387647

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.

Upvotes: 5

Related Questions