public static String getXPathExpression ( Node node ) { Object xpathCache = node . getUserData ( FULL_XPATH_CACHE ) ; if ( xpathCache != null ) { return xpathCache . toString ( ) ; } Node parent = node . getParentNode ( ) ; if ( ( parent == null ) || parent . getNodeName ( ) . contains ( "#document" ) ) { String xPath = "/" + node . getNodeName ( ) + "[1]" ; node . setUserData ( FULL_XPATH_CACHE , xPath , null ) ; return xPath ; } if ( node . hasAttributes ( ) && node . getAttributes ( ) . getNamedItem ( "id" ) != null ) { String xPath = "//" + node . getNodeName ( ) + "[@id = '" + node . getAttributes ( ) . getNamedItem ( "id" ) . getNodeValue ( ) + "']" ; node . setUserData ( FULL_XPATH_CACHE , xPath , null ) ; return xPath ; } StringBuffer buffer = new StringBuffer ( ) ; if ( parent != node ) { buffer . append ( getXPathExpression ( parent ) ) ; buffer . append ( "/" ) ; } buffer . append ( node . getNodeName ( ) ) ; List < Node > mySiblings = getSiblings ( parent , node ) ; for ( int i = 0 ; i < mySiblings . size ( ) ; i ++ ) { Node el = mySiblings . get ( i ) ; if ( el . equals ( node ) ) { buffer . append ( ' ' ) . append ( Integer . toString ( i + 1 ) ) . append ( ' ' ) ; // Found so break; break ; } } String xPath = buffer . toString ( ) ; node . setUserData ( FULL_XPATH_CACHE , xPath , null ) ; return xPath ; }
Reverse Engineers an XPath Expression of a given Node in the DOM .