Find element by text with XPath in ElementTree

pistacchio picture pistacchio · May 31, 2012 · Viewed 36.8k times · Source

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

Answer

brandizzi picture brandizzi · May 31, 2012

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