Python XpathEvaluator without namespace

雨燕双飞 提交于 2019-12-10 09:44:01

问题


I need to write a dynamic function that finds elements on a subtree of an ATOM xml document.

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)

The code above fails to find category.

The reason is that getpath returns an XPath without namespaces, whereas the XPathEvaluator e() requires namespaces.

Is there a way to either make getpath return namespaces in the path, or allow XPathEvaluator to accept the path without specifying the namespace (or, rather, specifying it some other way)?


回答1:


Use:

*[local-name() = 'category']

Or, if you want to be more precise:

*[local-name() = 'category' and namespace-uri() = 'http://www.w3.org/2005/Atom']

Or simply:

def:category


来源:https://stackoverflow.com/questions/13091717/python-xpathevaluator-without-namespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!