共用方式為


按索引順序擷取節點

萬維網聯合會 (W3C) XML 檔案物件模型 (DOM) 也描述 NodeList,其能夠處理已排序的節點清單,而不是 XmlNamedNodeMap 所處理的未排序集合。 Microsoft .NET Framework 中的 NodeList 稱為 XmlNodeList。 傳回 XmlNodeList 的方法和屬性如下:

  • XmlNode.ChildNodes

  • XmlDocument.GetElementsByTagName

  • XmlElement.GetElementsByTagName

  • XmlNode.SelectNodes

XmlNodeList 具有 Count 屬性,可用來撰寫迴圈來逐一查看 XmlNodeList 中的節點,如下列程式代碼範例所示:

Dim doc as XmlDocument = new XmlDocument()  
   doc.Load("books.xml")  
  
    ' Retrieve all book titles.  
    Dim root as XmlElement = doc.DocumentElement  
    Dim elemList as XmlNodeList = root.GetElementsByTagName("title")  
    Dim i as integer  
    for i=0  to elemList.Count-1  
        ' Display all book titles in the Node List.  
        Console.WriteLine(elemList.ItemOf(i).InnerXml)  
    next  
XmlDocument doc = new XmlDocument();  
doc.Load("books.xml");  
// Retrieve all book titles.  
XmlElement root = doc.DocumentElement;  
XmlNodeList elemList = root.GetElementsByTagName("title");  
for (int i=0; i < elemList.Count; i++)  
{
   // Display all book titles in the Node List.  
   Console.WriteLine(elemList[i].InnerXml);  
}

除了 Count 屬性之外,還有 GetEnumerator 方法可用於以foreach樣式迭代 XmlNodeList 中的節點集合。 下列程式代碼範例示範 語句的使用 foreach

Dim doc As New XmlDocument()  
doc.Load("books.xml")  
  
' Get book titles.  
Dim root As XmlElement = doc.DocumentElement  
Dim elemList As XmlNodeList = root.GetElementsByTagName("title")  
Dim ienum As IEnumerator = elemList.GetEnumerator()  
' Loop over the XmlNodeList using the enumerator ienum
While ienum.MoveNext()  
    ' Display the book title.  
    Dim title As XmlNode = CType(ienum.Current, XmlNode)  
    Console.WriteLine(title.InnerText)  
End While  
{  
     XmlDocument doc = new XmlDocument();  
     doc.Load("books.xml");  
  
     // Get book titles.  
     XmlElement root = doc.DocumentElement;  
     XmlNodeList elemList = root.GetElementsByTagName("title");  
     IEnumerator ienum = elemList.GetEnumerator();
     // Loop over the XmlNodeList using the enumerator ienum
     while (ienum.MoveNext())  
     {  
          // Display the book title.  
           XmlNode title = (XmlNode) ienum.Current;  
           Console.WriteLine(title.InnerText);  
     }  
  }  

如需 XmlNodeList 上可用方法和屬性的詳細資訊,請參閱 XmlNodeList

另請參閱