python - 使用 ElementTree 进行 XPath 搜索

标签 python xml xpath

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

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

搜索带有“Two”的 child 并返回 true/false

如果它是这样开始的

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

这是如何实现的

最佳答案

我最近一直在玩 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 支持,但它并没有说完全不支持。

关于python - 使用 ElementTree 进行 XPath 搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/238697/

相关文章:

python - 在python中读取具有混合数据类型的未知大小的二进制文件

python - 对表达式执行简化时出现关键错误

java - 使用 Java 读取 XML 中的 XML

java - 更改为 Android SDK 26 后工具栏中的图标被压扁

python selenium 找不到 iframe xpath

java - 线程 "main"org.openqa.selenium.NoSuchElementException : Unable to locate element://*[@id ='login-email' ] 中的异常

python - 我的 xpath 表达式有什么问题?

python - 我如何同时比较不同数据框中的两列?

python - 如果有详细信息,pandas 会排除总数

c# - LINQ 值查询返回错误的字符串