Search code examples
pythonxmlgetelementsbytagname

How to do getElementsByTagName() using ElementTree?


I've used Python's miniDom library before. It had a useful method that I'm missing in the ElementTree library :

getElementsByTagName('bar')

getElementsByTagName() finds all children of a given name, no matter how deep, thus working recursively. This is usually good, but can cause problems if similar nodes exist at multiple levels and the intervening nodes are important.

source: http://wiki.python.org/moin/MiniDom

Does such a function also exist in ElementTree? I've looked through the docs, but couldn't find it.


Solution

  • ElementTree uses an XPath subset for selecting nodes within the XML tree. You can use tree.findall( './/bar' ) to find all bar nodes within the tree.