Overview
The XmlNodeList class provides an ordered collection of nodes from an XmlDocument. It implements IEnumerable and allows iteration over the nodes it contains.
Syntax
public abstract class XmlNodeList : IEnumerable, IEnumerable<XmlNode>
Properties
| Name | Type | Description |
|---|---|---|
Count | int | Gets the number of nodes in the list. |
Item | XmlNode | Gets the node at the specified index. |
this[int index] | XmlNode | Indexer to retrieve a node by its position. |
Methods
| Name | Signature | Description |
|---|---|---|
GetEnumerator | IEnumerator GetEnumerator() | Returns an enumerator that iterates through the collection. |
CopyTo | void CopyTo(Array array, int index) | Copies the entire collection to a compatible one-dimensional array, starting at the specified index. |
Examples
The following example loads an XML document and retrieves a list of all <book> elements.
using System;
using System.Xml;
class Program
{
static void Main()
{
var xml = @"<catalog>
<book id='b1'>
<title>XML Developer's Guide</title>
</book>
<book id='b2'>
<title>Midnight Rain</title>
</book>
</catalog>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNodeList books = doc.GetElementsByTagName("book");
Console.WriteLine($"Found {books.Count} books:");
foreach (XmlNode book in books)
{
Console.WriteLine($"- {book.Attributes[""id""].Value}: {book[""title""].InnerText}");
}
}
}
Remarks
- The collection is live; changes to the underlying
XmlDocumentare reflected in theXmlNodeList. - Instances of
XmlNodeListare typically obtained via methods such asXmlElement.GetElementsByTagNameorXmlNode.SelectNodes. - Because the list implements
IEnumerable, you can useforeachin C# orfor...ofin JavaScript (via COM interop) to iterate.