Pobieranie uporządkowanych węzłów na podstawie indeksu

Model obiektów dokumentowych XML (DOM) World Wide Web Consortium (W3C) opisuje również bibliotekę NodeList, która ma możliwość obsługi uporządkowanej listy węzłów, w przeciwieństwie do zestawu nieuporządkowanego obsługiwanego przez obiekt XmlNamedNodeMap. Lista NodeList w programie Microsoft .NET Framework nosi nazwę XmlNodeList. Metody i właściwości zwracające element XmlNodeList to:

  • XmlNode.ChildNodes

  • XmlDocument.GetElementsByTagName

  • XmlElement.GetElementsByTagName

  • XmlNode.SelectNodes

Obiekt XmlNodeList ma właściwość Count , która może służyć do pisania pętli w celu iteracji węzłów w pliku XmlNodeList, jak pokazano w poniższym przykładzie kodu:

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);  
}

Oprócz właściwości Count istnieje metoda GetEnumerator , która zapewnia foreach iterację stylu dla kolekcji węzłów w xmlNodeList. Poniższy przykład kodu przedstawia użycie instrukcji 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);  
     }  
  }  

Aby uzyskać więcej informacji na temat metod i właściwości dostępnych w kodzie XmlNodeList, zobacz XmlNodeList.

Zobacz też