📜  获取 XML 文档中的元素数量 - 无论代码示例

📅  最后修改于: 2022-03-11 14:55:16.689000             🧑  作者: Mango

代码示例1
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

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

public class CountNoOfElements{

    public static void main(String args[]) throws Exception {
        String filepath = "test.xml";
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(filepath);

        NodeList nodeList = doc.getElementsByTagName("*");
        int count = nodeList.getLength();
        System.out.println("Total of elements : " + count);
    }   
}