I was asked this week to explain how to count the number of elements in an XML file. I quickly said to use the XPath count function and left it at that. After spending so much time using XSLT, I sometimes forget which functions are only available in XSLT, such as the count function.
It didn't take long for this person to return for more answers. She tried to use selectSingleNode("count(//doc/row)") to return the count, which obviously didn't work. As I began to explain the correct answer, several others gathered around because they have struggled with the same problem. This was a big red flag that others out there may need help with this too, so here you go.
There is an easy way to count the number of elements in an XML file. We have many XML files that contain recordsets. They have a row element for each row in the recordset, and an attribute for each column. All you have to do is use the selectNodes method to return the rows in a NodeList. You can then check the length property value of the NodeList. See the example below. I know this may seem basic to some of you, but hopefully it will help someone. I was surprised at how many people said they just loop through the file counting the records.
Sample XML:
<doc>
<row id="1" value="10"/>
<row id="2" value="11"/>
</doc>
Sample JScript:
var Doc = new ActiveXObject("MSXML2.DOMDocument.4.0");
Doc.async = false;
Doc.load("countingxml.xml");
var numRows = Doc.selectNodes("//doc/row");
WScript.Echo(numRows.length);