使用 ElementTree getpath() 动态获取 Xpath [英] Get Xpath dynamically using ElementTree getpath()

查看:35
本文介绍了使用 ElementTree getpath() 动态获取 Xpath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to write a dynamic function that finds elements on a subtree of an ATOM xml by building dynamically the XPath to the element.

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

To do so, I've written something like this:

    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() 需要命名空间.

The code above fails to find "category" because getpath() returns an XPath without namespaces, whereas the XPathEvaluator e() requires namespaces.

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

Although I know I can use the path and provide a namespace in the call to XPathEvaluator, I would like to know if it's possible to make getpath() return a "fully qualified" path, using all the namespaces, as this is convenient in certain cases.

(这是我之前问题的衍生问题:没有命名空间的 Python XpathEvaluator)

(This is a spin-off question of my earlier question: Python XpathEvaluator without namespace)

推荐答案

与其尝试从根构建完整路径,您还可以使用条目作为基节点来计算 XPath 表达式:

Rather than trying to construct a full path from the root, you can evaluate XPath expression on with the entry as the base node:

tree = etree.parse(xmlFileUrl)
nsmap = {'def':'http://www.w3.org/2005/Atom'}
entries_expr = etree.XPath('//def:entry', namespaces=nsmap)
category_expr = etree.XPath('category')
for entry in entries_expr(tree):
    category = category_expr(entry)

如果性能不重要,您可以通过对元素使用 .xpath() 方法而不是预编译表达式来简化代码:

If performance is not critical, you can simplify the code by using the .xpath() method on elements rather than pre-compiled expressions:

tree = etree.parse(xmlFileUrl)
nsmap = {'def':'http://www.w3.org/2005/Atom'}
for entry in tree.xpath('//def:entry', namespaces=nsmap):
    category = entry.xpath('category')

这篇关于使用 ElementTree getpath() 动态获取 Xpath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆