Count XML Elements in the DOM

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);

Print | posted @ Thursday, August 17, 2006 7:57 PM

Comments on this entry:

Gravatar # re: Count XML Elements in the DOM
by abhishek at 7/8/2008 5:51 AM

hi,

can you help me out in the case if i have different names of each node or element.

that is in ur case u hd mentioned row,but if its like ..
<doc>
<row id="1" value="10"/>
<column id ="2" value="11"/>

</doc>

now i hv to count the no. of elements..then wht should i'be doing...?
Gravatar # re: Count XML Elements in the DOM
by John Workman at 7/9/2008 11:33 PM

you can do:
var numRows = Doc.selectNodes("//doc/*");
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
Twitter