问题
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