Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get leaf nodes - XML parsing in Java

Tags:

java

xml

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

like image 530
user3089869 Avatar asked Feb 14 '23 07:02

user3089869


1 Answers

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
like image 94
vanje Avatar answered Feb 20 '23 11:02

vanje