Serbin
Serbin

Reputation: 823

Find all elements in ElementTree by attribute using Python

I have an xml, which has a lot of different nodes with the different tags, but the same attribute. Is it possible to find all these nodes?

I know, that it is possible to find all nodes by attribute, if they all have the same tag:

root.findall(".//tag[@attrib]")

but in my case they all have different tags. Something like this is not working:

root.findall(".//[@attrib]")

Upvotes: 4

Views: 5527

Answers (1)

har07
har07

Reputation: 89325

In XPath you can use * to reference element of any name, and you can use @* to reference attribute of any name :

root.findall(".//*[@attrib]")

side notes :

As a heads up, if you're really using lxml (not just accidentally tagged the question with ), I would suggest to use xpath() method instead of findall(). The former has much better XPath support. For example, when you need to find element of limited set of names, say foo and bar, you can use the following XPath expression with xpath() method :

root.xpath("//*[self::foo or self::bar][@attrib]")

The same expression above when passed to findall() will result in an error :

SyntaxError: prefix 'self' not found in prefix map

Upvotes: 6

Related Questions