Find element by text with XPath in ElementTree

AFAIK ElementTree does not support XPath. Has it changed?

Anyway, you can use lxml and the following XPath expression:

import lxml.etree
doc = lxml.etree.parse('t.xml')
print doc.xpath('//element[text()="A"]')[0].text
print doc.xpath('//element[text()="A"]')[0].tag

The result will be:

A
element

Leave a Comment