Код ниже может работать.Идея состоит в том, чтобы подсчитать каждый элемент 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();
}
}