import java.io.ByteArrayInputStream;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class Main {
private static String getXPath(Node root, String elementName) {
for (int i = 0; i < root.getChildNodes().getLength(); i++) {
Node node = root.getChildNodes().item(i);
if (node instanceof Element == false) {
return null;
}
if (node.getNodeName().equals(elementName)) {
return "/" + node.getNodeName();
} else if (node.getChildNodes().getLength() > 0) {
String xpath = getXPath(node, elementName);
if (xpath != null) {
return "/" + node.getNodeName() + xpath;
}
}
}
return null;
}
private static String getXPath(Document document, String elementName) {
return document.getDocumentElement().getNodeName()
+ getXPath(document.getDocumentElement(), elementName);
}
public static void main(String[] args) throws Exception {
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, "test1");
Node node1 = (Node) XPathFactory.newInstance().newXPath().compile(xpath)
.evaluate(document, XPathConstants.NODE);
Node node2 = (Node) XPathFactory.newInstance().newXPath()
.compile("//test1").evaluate(document, XPathConstants.NODE);
System.out.println(node1.equals(node2));
}
}