gpt4 book ai didi

python - 使用 ElementTree getpath() 动态获取 Xpath

转载 作者:太空狗 更新时间:2023-10-30 01:09:28 24 4
gpt4 key购买 nike

我需要编写一个动态函数,通过动态构建元素的 XPath 在 ATOM xml 的子树上查找元素。

为此,我写了这样的东西:

    tree = etree.parse(xmlFileUrl)
e = etree.XPathEvaluator(tree, namespaces={'def':'http://www.w3.org/2005/Atom'})
entries = e('//def:entry')
for entry in entries:
mypath = tree.getpath(entry) + "/category"
category = e(mypath)

上面的代码找不到“类别”,因为 getpath() 返回一个没有命名空间的 XPath,而 XPathEvaluator e() 需要命名空间。

虽然我知道我可以使用路径并在对 XPathEvaluator 的调用中提供命名空间,但我想知道是否可以使用所有命名空间使 getpath() 返回“完全限定”路径,因为这是在某些情况下很方便。

(这是我之前问题的衍生问题:Python XpathEvaluator without namespace)

最佳答案

基本上,使用标准的Python 的xml.etree 库,需要一个不同的访问函数。要实现此范围,您可以像这样构建 iter 方法的修改版本:

def etree_iter_path(node, tag=None, path='.'):
if tag == "*":
tag = None
if tag is None or node.tag == tag:
yield node, path
for child in node:
_child_path = '%s/%s' % (path, child.tag)
for child, child_path in etree_iter_path(child, tag, path=_child_path):
yield child, child_path

然后你可以使用这个函数从根节点开始迭代树:

from xml.etree import ElementTree

xmldoc = ElementTree.parse(*path to xml file*)
for elem, path in etree_iter_path(xmldoc.getroot()):
print(elem, path)

关于python - 使用 ElementTree getpath() 动态获取 Xpath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13136334/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com