简体   繁体   中英

total number of nodes in xml

I need to get the total number of nodes in an xml file for Elements we use
NodeList nodeList = doc.getElementsByTagName("*"); but for nodes if you have any idea Thank you

The code below might work. The idea is to count each element of an XML file (and also its child elements), using recursion.

public class Main {

    int totalNodes = 0;

    public Main() throws Exception {
        String file = getClass().getResource("/test.xml").getFile();
        File fXmlFile = new File(file);
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);
        countNodes(doc.getDocumentElement());
        System.out.println(totalNodes);
    }

    public void countNodes(Node node) {
        System.out.println(node.getNodeName());
        totalNodes++;
        NodeList nodeList = node.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node currentNode = nodeList.item(i);
            if (currentNode.getNodeType() == Node.ELEMENT_NODE) {                    
                countNodes(currentNode);
            }
        }
    }

    public static void main(String[] args) throws Exception {
        new Main();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM