java code to get all leaf nodes of a xml file

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

showing results for - "java code to get all leaf nodes of a xml file"
Erwann
21 Aug 2020
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}