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/