在ElementTree中使用XPath通过文本查找元素
问题描述:
给出如下所示的XML:
Given an XML like the following:
<root>
<element>A</element>
<element>B</element>
</root>
如何使用ElementTree及其对XPath的支持将元素与内容A相匹配?谢谢
How can I match the element with content A using ElementTree and its support for XPath? Thanks
答
AFAIK ElementTree不支持XPath.变了吗?
AFAIK ElementTree does not support XPath. Has it changed?
无论如何,您可以使用 lxml 和以下XPath表达式:
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
结果将是:
A
element