【发布时间】:2018-11-30 16:43:48
【问题描述】:
我需要获取 xml 文件中的节点总数
对于我们使用的元素NodeList nodeList = doc.getElementsByTagName("*");
但是对于节点,如果您有任何想法
谢谢你
【问题讨论】:
-
最好更明确地说明您要计算哪些节点。属性?命名空间?空白文本节点?实体和 CDATA 节点?
我需要获取 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();
}
}
【讨论】: