[英]Find element by text with XPath in ElementTree
Given an XML like the following:给定一个如下的 XML:
<root>
<element>A</element>
<element>B</element>
</root>
How can I match the element with content A using ElementTree and its support for XPath?如何使用 ElementTree 及其对 XPath 的支持将元素与内容 A 匹配? Thanks谢谢
AFAIK ElementTree does not support XPath. AFAIK ElementTree 不支持 XPath。 Has it changed?有没有改变?
Anyway, you can use lxml and the following XPath expression:无论如何,您可以使用lxml和以下 XPath 表达式:
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
If you want to use the standard library ElementTree , rather than lxml, you can use iteration to find all sub elements with a particular text value.如果您想使用标准库ElementTree而不是 lxml,您可以使用迭代来查找具有特定文本值的所有子元素。 For example:例如:
import sys
import xml.etree.ElementTree as etree
s = """<root>
<element>A</element>
<element>B</element>
</root>"""
e = etree.fromstring(s)
if sys.version_info < (2, 7):
found = [element for element in e.getiterator() if element.text == 'A']
else:
found = [element for element in e.iter() if element.text == 'A']
print found[0].text # This prints 'A', honestly!
Note: you may want to perform some stripping of the text
value of your elements in the list comprehension.注意:您可能希望在列表理解中对元素的text
值进行一些剥离。
Edit This will work to any depth in your XML tree.编辑这将适用于您的 XML 树中的任何深度。 For example,例如,
s = """<root>
<element>A</element>
<element><sub>A</sub></element>
</root>"""
found = [element for element in e.getiterator() if element.text == 'A']
for f in found:
print f
will print将打印
<Element element at 7f20a882e3f8>
<Element sub at 7f20a882e4d0>
You can use XPath in ElementTree .您可以在 ElementTree 中使用XPath 。 It isn't necessary to install any lib.不需要安装任何库。
config.findall('.//*[element="A"]/element')
As the comment bellow from @Bionicegenius explains, the expression above just works if your element has no sibilings, but you get the idea.正如@Bionicegenius 的评论所解释的那样,如果您的元素没有兄弟姐妹,上面的表达式才有效,但您明白了。
It is possible to use XPath in ElementTree , and it is the simplest solution.可以在 ElementTree 中使用 XPath ,这是最简单的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.