java - count nodes in an xml file - Stack Overflow

java - count nodes in an xml file - Stack Overflow

java - count nodes in an xml file - Stack Overflow

You can use the excellent dom4j library and XPath to get a quick count:

List docNodes = document.selectNodes ("// collectionPrintable / document"); docNodes.size (); // The number of all "document" nodes directly // under a "collectionPrintable" node.

Map

If you want the number of "document" nodes under each "collectionCategory" you could do something like the code below which works with dom4j v1.6.1: ; numDocsPerCat = new HashMap (); String xpath = "// collectionCategory / collectionPrintable / document"; List & lt; Node & gt; docNodes = document.selectNodes (xpath); for (Node n: docNodes) {Node catNameNode = n.selectSingleNode ("././ name"); if (catNameNode! = null) {String categoryName = catNameNode.getText (); Integer count = numDocsPerCat.get (categoryName); numDocsPerCat.put (categoryName, (count == null)? 1: count + 1); }} System.out.println (numDocsPerCat); // {Arroces: 20, Aves: 20, Meats: 2}

Once you have executed this code the numDocsPerCat map will have entries such as: numDocsPerCat.get (" "); // = & gt; 20

Related news