Java tutorial
//package com.java2s; //License from project: Apache License import java.util.ArrayList; import java.util.List; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { private static final String FULL_XPATH_CACHE = "FULL_XPATH_CACHE"; /** * Reverse Engineers an XPath Expression of a given Node in the DOM. * * @param node * the given node. * @return string xpath expression (e.g., "/html[1]/body[1]/div[3]"). */ 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; } 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; } /** * Get siblings of the same type as element from parent. * * @param parent * parent node. * @param element * element. * @return List of sibling (from element) under parent */ public static List<Node> getSiblings(Node parent, Node element) { List<Node> result = new ArrayList<Node>(); NodeList list = parent.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node el = list.item(i); if (el.getNodeName().equals(element.getNodeName())) { result.add(el); } } return result; } }