fork download
  1. import java.io.ByteArrayInputStream;
  2. import javax.xml.parsers.DocumentBuilderFactory;
  3. import org.w3c.dom.Document;
  4. import org.w3c.dom.Element;
  5. import org.w3c.dom.Node;
  6. import javax.xml.xpath.*;
  7.  
  8. public class Main{
  9.  
  10. public static void main(String[] args) {
  11. try
  12. {
  13. Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(
  14. ("<foo><foo1>Foo Test 1</foo1><foo2><another1><test1>Foo Test 2</test1></another1></foo2><foo3>Foo Test 3</foo3><foo4>Foo Test 4</foo4></foo>").getBytes()
  15. )
  16. );
  17.  
  18. String xpath = getXPath(document, "another1");
  19. System.out.println(xpath);
  20.  
  21. }
  22. catch (Exception e)
  23. {
  24. e.printStackTrace();
  25. }
  26.  
  27.  
  28. }
  29.  
  30. private static String getXPath(Document root, String elementName) throws XPathExpressionException
  31. {
  32. XPathExpression expr = XPathFactory.newInstance().newXPath().compile("//" + elementName);
  33. Node node = (Node)expr.evaluate(root, XPathConstants.NODE);
  34.  
  35. if(node != null) {
  36. return getXPath(node);
  37. }
  38.  
  39. return null;
  40. }
  41.  
  42. private static String getXPath(Node node) {
  43. if(node == null || node.getNodeType() != Node.ELEMENT_NODE) {
  44. return "";
  45. }
  46.  
  47. return getXPath(node.getParentNode()) + "/" + node.getNodeName();
  48. }
  49.  
  50. }
Success #stdin #stdout 0.09s 246144KB
stdin
Standard input is empty
stdout
/foo/foo2/another1