[英]total number of nodes in xml
我需要獲取我們使用的Elements的xml文件中的節點總數
NodeList nodeList = doc.getElementsByTagName("*");
但是對於節點,如果您有任何想法,謝謝
下面的代碼可能有效。 這個想法是使用遞歸對XML文件的每個元素(及其子元素)進行計數。
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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.