Find element by text with XPath in ElementTree

elementtree, python, xml, xpath

Solution

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

Problem

Given an XML like the following: ``` <root> <element>A</element> <element>B</element> </root> ``` How can I match the element with content A using ElementTree and its support for XPath? Thanks

Original source