import java.io.ByteArrayInputStream;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import javax.xml.xpath.*;

public class Main{

public static void main(String[] args) {
    try 
    {
      Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(
        new ByteArrayInputStream(
          ("<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()
        )
      );

      String xpath = getXPath(document, "another1");
      System.out.println(xpath);        

    }
    catch (Exception e) 
    {
      e.printStackTrace();
    }
    
    
}

private static String getXPath(Document root, String elementName) throws XPathExpressionException 
{
  XPathExpression expr = XPathFactory.newInstance().newXPath().compile("//" + elementName);
  Node node = (Node)expr.evaluate(root, XPathConstants.NODE);

  if(node != null) {
      return getXPath(node);
  }

  return null;
}

private static String getXPath(Node node) {
    if(node == null || node.getNodeType() != Node.ELEMENT_NODE) {
        return "";
    }

    return getXPath(node.getParentNode()) + "/" + node.getNodeName();
}

}