Find all elements in ElementTree by attribute using Python
Asked Answered
P

1

4

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]")
Predestinate answered 15/10, 2015 at 6:19 Comment(0)
C
6

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

Crystallite answered 15/10, 2015 at 6:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.