Microsoft XML SDK 2.6 - XML Developer's Guide

Using Collections

In the XML DOM, collections are used to store lists of nodes or elements. The XMLDOMNodeList object is a collection; it is returned by childNodes, selectNodes, and getElementsByTagName. Unlike an array, a collection is dynamic, meaning that the addition or removal of nodes, and changes within nodes, are immediately reflected in the collection.

Accessing Collection Members

Use the item method to access individual nodes within a collection. For example, the following code returns the first member of the collection:

objNodeList.item(0) 

As a shortcut, you can access a node by simply appending the appropriate index number in parentheses to a collection reference, like so:

objNodeList(0)

You can also use square brackets to enclose the index number (except in VBScript):

objNodeList[0]

Iterating a Collection

In Visual Basic, you can iterate through an XML DOM collection with a For Each…Next statement, like so:

Dim Item
For Each Item in objNodeList
   MsgBox Item.text
Next

Or you can use a For…Next statement:

Dim i
Dim members
members = objNodeList.length
For i = 0 To (members-1)
   MsgBox objNodeList(i).xml
Next

The length property returns the number of members in the collection.

Optimize your script by setting the node list to a variable and using that variable in a For loop. This way, the script engine does not have to examine the collection during each iteration.

You can iterate collections in JScript this way:

var members = objNodeList.length;
for (var i = 0; i < members; i++)
{
   alert (objNodeList(i).text);
}