java code to get all leaf nodes of a xml

java code to get all leaf nodes of a xml

To get all leaf nodes of an XML document in Java, you can use the NodeList and Node classes from the org.w3c.dom package.

Here is an example of how to get all leaf nodes of an XML document:

re‮l:ot ref‬autturi.com
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
  public static void main(String[] args) {
    try {
      File xmlFile = new File("example.xml");
      DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
      Document doc = dBuilder.parse(xmlFile);

      NodeList nodes = doc.getChildNodes();
      for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE && node.getChildNodes().getLength() == 1 && node.getFirstChild().getNodeType() == Node.TEXT_NODE) {
          System.out.println(node.getNodeName() + ": " + node.getTextContent());
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

In this example, the File, DocumentBuilderFactory, and DocumentBuilder classes are used to parse the XML file and create a Document object that represents the XML document. The getChildNodes method is used to get a NodeList containing all child nodes of the document.

The for loop iterates over the nodes in the list and checks if each node is an element node (Node.ELEMENT_NODE) with a single child node that is a text node (Node.TEXT_NODE). If these conditions are met, the node is considered a leaf node, and its name and text content are output to the console using the getNodeName and getTextContent methods.

You can modify this example to suit your specific needs, such as filtering the nodes based on their names or attributes, or handling different types of XML documents.

Created Time:2017-11-03 00:14:50  Author:lautturi