I'm using Java 1.6.  Given a org.w3c.dom.Node object, how do I get a String XPath expression for where that node falls in an XML document?  It is NOT a given that this node or any of its ancestors/descendants have an id attribute.
            Asked
            
        
        
            Active
            
        
            Viewed 1,718 times
        
    1
            
            
        - 
                    1This has been answered many times for JavaScript on SO. You might get some use out of looking at some of those answers. Like this one: http://stackoverflow.com/questions/2661818/javascript-get-xpath-of-a-node – Wayne Dec 07 '11 at 15:16
 
2 Answers
1
            I don't believe there is any easy way via DOM. The problem is that there is not a single canonical way to identify a given node.
Having said that, you might find the the function getXPath from diffxml useful: http://diffxml.cvs.sourceforge.net/viewvc/diffxml/diffxml/src/java/org/diffxml/diffxml/fmes/NodeOps.java?view=markup
It will return an XPath of the form /node()[4]/node()[2] etc.
UPDATE: As diffxml is GPL licensed and getXPath takes a bit of extracting, I released it as XPathGen on github: https://github.com/amouat/XPathGen under an Apache licence.
        Adrian Mouat
        
- 44,585
 - 16
 - 110
 - 102
 
- 
                    There might not be a *canonical* way to represent a node, but you can always do it accurately by position. – Wayne Dec 07 '11 at 15:17
 - 
                    
 
0
            
            
        You could pass your node and an empty string to a recursive method such as this one:
static void xpm(Node node, String xpath){
    if (node.getParentNode()==null){
        System.out.println(xpath);
        return;
    }
    xpath = "/"+node.getNodeName()+xpath;
    node = node.getParentNode();
    xpm(node, xpath);
}
        Milka
        
- 297
 - 2
 - 11