java code to get all leaf nodes of a xml

Solutions on MaxInterview for java code to get all leaf nodes of a xml by the best coders in the world

showing results for - "java code to get all leaf nodes of a xml"
Joachim
28 Nov 2019
1try {
2  final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("input.xml");
3  final XPathExpression xpath = XPathFactory.newInstance().newXPath().compile("//*[count(./*) = 0]");
4  final NodeList nodeList = (NodeList) xpath.evaluate(doc, XPathConstants.NODESET);
5  for(int i = 0; i < nodeList.getLength(); i++) {
6    final Element el = (Element) nodeList.item(i);
7    System.out.println(el.getNodeName());
8  }
9} catch (Exception e) {
10  e.printStackTrace();
11}
similar questions
queries leading to this page
java code to get all leaf nodes of a xml