Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Xpath from the org.w3c.dom.Node

Tags:

Can i get the full xpath from the org.w3c.dom.Node ?

Say currently node is pointing to some where the middle of the xml document. I would like extract the xpath for that element.

The output xpath I'm looking for is //parent/child1/chiild2/child3/node. A parent to node xpath. Just ignore the xpath's which are having expressions and points to the same node.

like image 422
srinannapa Avatar asked Feb 18 '11 20:02

srinannapa


1 Answers

There's no generic method for getting the XPath, mainly because there's no one generic XPath that identifies a particular node in the document. In some schemas, nodes will be uniquely identified by an attribute (id and name are probably the most common attributes.) In others, the name of each element (that is, the tag) is enough to uniquely identify a node. In a few (unlikely, but possible) cases, there's no one unique name or attribute that takes you to a specific node, and so you'd need to use cardinality (get the n'th child of the m'th child of...).

EDIT: In most cases, it's not hard to create a schema-dependent function to assemble an XPath for a given node. For example, suppose you have a document where every node is uniquely identified by an id attribute, and you're not using namespaces. Then (I think) the following pseudo-Java would work to return an XPath based on those attributes. (Warning: I have not tested this.)

String getXPath(Node node) {     Node parent = node.getParent();     if (parent == null) {         return "/" + node.getTagName();     }     return getXPath(parent) + "/" + "[@id='" + node.getAttribute("id") + "']"; } 
like image 90
Dan Breslau Avatar answered Nov 18 '22 06:11

Dan Breslau