次の方法で共有


インデックスによる順序付きノードの取得

World Wide Web Consortium (W3C) XML Document Object Model (DOM) では、ノードの順序付きリストを処理する機能を持つ NodeList も記述されています。これは、 XmlNamedNodeMap によって処理される順序なしセットとは対照的です。 Microsoft .NET Framework の NodeList は XmlNodeList と呼ばれます。 XmlNodeList を返すメソッドとプロパティは次のとおりです。

  • XmlNode.ChildNodes

  • XmlDocument.GetElementsByTagName

  • XmlElement.GetElementsByTagName

  • XmlNode.SelectNodes

XmlNodeList には、次のコード サンプルに示すように、XmlNodeList 内のノードを反復処理するループを記述するために使用できる Count プロパティがあります。

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 プロパティに加えて、XmlNodeList 内のノードのコレクションに対するforeachスタイルの反復処理を提供する GetEnumerator メソッドがあります。 次のコード例は、 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を参照してください。

こちらも参照ください