Geeks With Blogs
John Workman The Workdog's weblog.... a brain dump, of sorts.

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:


  <row id="1" value="10"/>

  <row id="2" value="11"/>


Sample JScript:

var Doc = new ActiveXObject("MSXML2.DOMDocument.4.0");

Doc.async = false;


var numRows = Doc.selectNodes("//doc/row");


Posted on Thursday, August 17, 2006 7:57 PM | Back to top

Comments on this post: Count XML Elements in the DOM

# re: Count XML Elements in the DOM
Requesting Gravatar...

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 ..
<row id="1" value="10"/>
<column id ="2" value="11"/>


now i hv to count the no. of elements..then wht should i'be doing...?
Left by abhishek on Jul 08, 2008 5:51 AM

# re: Count XML Elements in the DOM
Requesting Gravatar...
you can do:
var numRows = Doc.selectNodes("//doc/*");
Left by John Workman on Jul 09, 2008 11:33 PM

Your comment:
 (will show your gravatar)

Copyright © John Workman | Powered by: