使用ElementTree进行XPath搜索

4 投票
2 回答
3411 浏览
提问于 2025-04-11 09:30

我刚接触xml,想用Python的ElementTree格式来查找xml文件里的内容,想知道怎么用XPath来做这件事。

<root>
<child>One</child>
<child>Two</child>
<child>Three</child>
</root>

我想查找一个名为"Two"的子元素,并返回真或假。

如果一开始是这样的:

from elementtree import ElementTree
root = ElementTree.parse(open(PathFile)).getroot()

那我该怎么实现呢?

2 个回答

1

当我们评估以下的XPath表达式时:

    boolean(/*/*[.='Two'])

如果存在一个元素(这个元素是顶层元素的子元素,并且它的字符串值等于"Two"),那么结果就是true

如果没有这样的元素,结果就是false

希望这对你有帮助。

祝好,

Dimitre Novatchev

1

我最近在玩ElementTree,看看这个..

>>> from xml.etree import ElementTree
>>> help(ElementTree.ElementPath)
>>> root = ElementTree.fromstring("""
<root><child>One</child><child>Two</child><child>Three</child></root>
""")
>>> ElementTree.ElementPath.findall(root, "child")
[<Element child at 2ac98c0>, <Element child at 2ac9638>, <Element child at 2ac9518>]
>>> elements = ElementTree.ElementPath.findall(root, "child")
>>> two = [x for x in elements if x.text == "Two"]
>>> two[0].text
'Two'

这就是你想要的对吧?它说ElementPath对xpath的支持有限,不过并没有说完全不支持。

撰写回答