4

xml 新手。寻找 XPath 以搜索具有 python ElementTree 格式的 xml 文件

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

用“二”搜索孩子并返回真/假

如果它开始像

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

如何做到这一点

4

2 回答 2

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 支持,但它并没有说根本不支持。

于 2008-10-27T09:32:36.830 回答
1

当计算以下 XPath 表达式时:

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

结果为true,如果存在这样的元素(顶部元素的子元素,其字符串值等于“Two”),

否则为假。

希望这有帮助。

干杯,

迪米特·诺瓦切夫

于 2008-11-12T23:00:26.673 回答