Hi, I use the "tree.getpath(element)" to solve a problem, and I need to have a meaningful path. In the example at http://pastebin.com/1Xjprfui the getpath method behaves exactly as expected when I use it in an XML doc with no namespace or if all elements have a namespace prefix (examples 1 and 3). But if I use tree.getpath(element) on a document with a default namespace (second example), I got weird getpath results like "/*", "/*/*/*[2]" and so on when I expected meaningful path like "/root", "/root/parent/child[2]". Is this a bug or a feature ? If a feature, is there some workaround to get meaningful path expressions ? Thanks in advance for any help. -- Gilles Lenfant
Hi,
On 20.07.2015, at 14:37, Gilles Lenfant <gilles.lenfant@gmail.com> wrote:
I use the "tree.getpath(element)" to solve a problem, and I need to have a meaningful path.
The documentation of getpath states:
For namespaced elements, the expression uses prefixes from the document, which therefore need to be provided in order to make any use of the expression in XPath.
So, I guess you have to set a prefix for the namespace, e.g. by creating a new root Element with the nsmap parameter set. jens
Thanks Jens, This makes sense now ! Unfortunately I have cannot change the XML input files that are provided by my customer. For those who follow this issue, here's my solutions : def print_paths(xml_text): root = etree.XML(xml_text) if None in root.nsmap: # Default namespace (no prefix) new_nsmap = root.nsmap.copy() del new_nsmap[None] new_root = etree.Element(root.tag, nsmap=new_nsmap) for elem in root: new_root.append(elem) root = new_root tree = root.getroottree() print root.nsmap for element in root.iter(): print element.tag, tree.getpath(element) 2015-07-20 14:57 GMT+02:00 Jens Quade <jq@qdevelop.de>:
Hi,
On 20.07.2015, at 14:37, Gilles Lenfant <gilles.lenfant@gmail.com> wrote:
I use the "tree.getpath(element)" to solve a problem, and I need to have a meaningful path.
The documentation of getpath states:
For namespaced elements, the expression uses prefixes from the document, which therefore need to be provided in order to make any use of the expression in XPath.
So, I guess you have to set a prefix for the namespace, e.g. by creating a new root Element with the nsmap parameter set.
jens
participants (2)
-
Gilles Lenfant
-
Jens Quade