XMLUtil { public static String getXPathForElement(Node e, NamespaceContext ctx) { StringBuffer sb = new StringBuffer(); List<Node> path = new ArrayList<Node>(); Node currentNode = e; while (currentNode.getParentNode() != currentNode.getOwnerDocument()) { path.add(0, currentNode); if (currentNode instanceof Attr) { Attr a = (Attr) currentNode; currentNode = a.getOwnerElement(); } else { currentNode = currentNode.getParentNode(); } } path.add(0, currentNode); for (Node n : path) { sb.append("/"); if (n.getNodeType() == Node.ATTRIBUTE_NODE) { sb.append("@"); } String namespaceURI = n.getNamespaceURI(); if (namespaceURI != null && !namespaceURI.equals("")) { sb.append(ctx.getPrefix(namespaceURI)).append(":"); } sb.append(n.getLocalName()); if (n.getNodeType() == Node.ELEMENT_NODE) { appendElementQualifier(sb, (Element)n); } } return sb.toString(); } private  XMLUtil(); static Document parseXML(String xmlAsString); static Document parseXML(InputStream in); static void writeXML(Node xml, File file); static void writeXML(Node xml, OutputStream outputStream); static void removeNodes(Element parent, NodeList elements); static List<Element> getChildElementsByName(Element element,
			String localName); static List<Element> getChildElements(Element element); static void addAsFirstChild(Element element, Element newChild); static QName getQName(Node n); static void removeAllSubNodesExceptAttributes(Node n); static Document createDocument(); static String getContentsOfTextOnlyNode(Node n); static String getXPathForElement(Node e, NamespaceContext ctx); static int getPosition(Element e); static Text appendTextNode(Element e, String contents); static String getTextContent(Node e); static QName resolveQName(String qNameWithPrefix, Element element); static String resolveNamespacePrefix(String prefix, Element element); static QName resolveQNameTargetNS(String sName, Node context, String targetNS);  }
@Test public void testGetXPathForElement() throws Exception { Document xml = XMLUtil.parseXML(getClass().getResourceAsStream("GetXPathForElement.xml")); SimpleNamespaceContext ctx = new SimpleNamespaceContext(); ctx.addNamespace("a", "a"); ctx.addNamespace("b", "b"); Element a = xml.getDocumentElement(); Element b = (Element) XMLUtil.getChildElementsByName(a, "B").get(0); Element c = (Element) XMLUtil.getChildElementsByName(b, "C").get(0); Element d1 = (Element) XMLUtil.getChildElementsByName(c, "D").get(0); Element d2 = (Element) XMLUtil.getChildElementsByName(c, "D").get(1); Element d3 = (Element) XMLUtil.getChildElementsByName(b, "D").get(0); Attr id = c.getAttributeNode("id"); assertEquals("/a:A/b:B/a:C", XMLUtil.getXPathForElement(c, ctx)); assertEquals("/a:A/b:B/a:C/@id", XMLUtil.getXPathForElement(id, ctx)); assertEquals("/a:A/b:B/a:C/a:D[@name='testName']", XMLUtil.getXPathForElement(d1, ctx)); assertEquals("/a:A/b:B/a:C/a:D[2]", XMLUtil.getXPathForElement(d2, ctx)); assertEquals("/a:A/b:B/a:D", XMLUtil.getXPathForElement(d3, ctx)); }