How to get the equivalent of getElementByID() with the Python library xml.etree.ElementTree?
There seems to be a method called parseid() but my tree is already parsed. I don't want to parse it again.
The accepted answer works indeed, but performance can be quite abysmal as - my guess is, I didn't verify this, perhaps also related to the complexity of xpath - the tree is traversed on every to findall(), which may or may not be a concern for your use case.
Probably parseid() is indeed what you want if performance is a concern. If you want to obtain such an id mapping on an existing tree, you can also easily perform the traversal once manually.
class getElementById():
def __init__(self, tree):
self.di = {}
def v(node):
i = node.attrib.get("id")
if i is not None:
self.di[i] = node
for child in node:
v(child)
v(tree.getroot())
def __call__(self, k):
return self.di[k]
I found it myself:
tree.findall('''.//*[@id='fooID']''')[0]
Better or other solutions are still welcome. :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With