If you pass the String
"Sequence_Number" then how could it know which of the Sequence_Number
siblings to get the XPath of? You could be talking about the first occurrence or maybe the second or third, it wont know. Given just a tagName, it can't know which occurrence to get the XPath for.
That said, the below method will give you the general XPath to where an element lives. You just need to get the org.w3c.dom.Element
first, which can be gotten from the org.w3c.dom.Document
.
public static String getXPathOfElement(org.w3c.dom.Element el) {
Objects.requireNonNull(el);
LinkedList<String> list = new LinkedList<>();
for (Node n = el; n != null; n = n.getParentNode()) {
if (n.getNodeType() == Node.ELEMENT_NODE)
list.push(n.getNodeName());
else
list.push("");
}
return String.join("/", list);
}
public static void main(String[] args)
throws ParserConfigurationException, SAXException, IOException {
// Get an input stream of your Xml somehow
String xml =
"<tXML xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
+ "<Header>"
+ "<Source>Source1</Source>"
+ "<Action_Type>Action_Type1</Action_Type>"
+ "<Sequence_Number>Sequence_Number1</Sequence_Number>"
+ "</Header>"
+ "</tXML>";
java.io.InputStream xmlInputStream = new java.io.ByteArrayInputStream(xml.getBytes());
// Get the Document from the xml InputStream
javax.xml.parsers.DocumentBuilderFactory docBuilderFact =
javax.xml.parsers.DocumentBuilderFactory.newInstance();
javax.xml.parsers.DocumentBuilder docBuilder = docBuilderFact.newDocumentBuilder();
org.w3c.dom.Document doc = docBuilder.parse(xmlInputStream);
// Get the Element you want the general XPath of
// In this case just find the first one with a certain tag in the Document
org.w3c.dom.Element el =
(org.w3c.dom.Element) doc.getElementsByTagName("Sequence_Number").item(0);
System.out.println(getXPathOfElement(el));
}