Is it possible to parse an XML and get all the leaf nodes ?
<root>
<emp>
<name>abc<name>
<age>12</age>
</emp>
<dept>
<branch>cse</branch>
</dept>
</root>
My output should be name age branch
Use this XPath expression to find alle elements which have no other elements as childs: //*[count(./*) = 0]
.
try {
final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("input.xml");
final XPathExpression xpath = XPathFactory.newInstance().newXPath().compile("//*[count(./*) = 0]");
final NodeList nodeList = (NodeList) xpath.evaluate(doc, XPathConstants.NODESET);
for(int i = 0; i < nodeList.getLength(); i++) {
final Element el = (Element) nodeList.item(i);
System.out.println(el.getNodeName());
}
} catch (Exception e) {
e.printStackTrace();
}
Result is
name
age
branch
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With