Uzyskiwanie dostępu do atrybutów w modelu DOM

Atrybuty są właściwościami elementu, a nie elementem podrzędnym elementu. To rozróżnienie jest ważne ze względu na metody używane do nawigowania po węzłach równorzędnych, nadrzędnych i podrzędnych modelu obiektów dokumentów XML (DOM). Na przykład metody PreviousSibling i NextSibling nie są używane do przechodzenia z elementu do atrybutu lub między atrybutami. Zamiast tego atrybut jest właściwością elementu i jest własnością elementu, ma właściwość OwnerElement , a nie właściwość parentNode i ma różne metody nawigacji.

Gdy bieżący węzeł jest elementem, użyj metody HasAttribute , aby sprawdzić, czy istnieją jakieś atrybuty skojarzone z elementem. Gdy wiadomo, że element ma atrybuty, istnieje wiele metod uzyskiwania dostępu do atrybutów. Aby pobrać pojedynczy atrybut z elementu, można użyć metod GetAttribute i GetAttributeNode elementu XmlElement lub uzyskać wszystkie atrybuty do kolekcji. Uzyskanie kolekcji jest przydatne, jeśli musisz wykonać iterację w kolekcji. Jeśli chcesz, aby wszystkie atrybuty z elementu, użyj właściwości Attributes elementu, aby pobrać wszystkie atrybuty do kolekcji.

Pobieranie wszystkich atrybutów do kolekcji

Jeśli chcesz umieścić wszystkie atrybuty węzła elementu w kolekcji, wywołaj właściwość XmlElement.Attributes . Spowoduje to pobranie klasy XmlAttributeCollection zawierającej wszystkie atrybuty elementu. Klasa XmlAttributeCollection dziedziczy z mapy XmlNamedNode. W związku z tym metody i właściwości dostępne w kolekcji obejmują te dostępne na mapie nazwanego węzła oprócz metod i właściwości specyficznych dla klasy XmlAttributeCollection, takich jak właściwość ItemOf lub metoda Append. Każdy element w kolekcji atrybutów reprezentuje węzeł XmlAttribute . Aby znaleźć liczbę atrybutów elementu, pobierz element XmlAttributeCollection i użyj właściwości Count , aby zobaczyć, ile węzłów XmlAttribute znajduje się w kolekcji.

Poniższy przykład kodu pokazuje, jak pobrać kolekcję atrybutów i, używając metody Count dla indeksu pętli, iterować nad nią. Następnie kod pokazuje, jak pobrać pojedynczy atrybut z kolekcji i wyświetlić jego wartość.

Imports System.IO
Imports System.Xml

Public Class Sample

    Public Shared Sub Main()

        Dim doc As XmlDocument = New XmlDocument()
        doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5' misc='sale item'>" & _
               "<title>The Handmaid's Tale</title>" & _
               "<price>14.95</price>" & _
               "</book>")

        ' Move to an element.
        Dim myElement As XmlElement = doc.DocumentElement

        ' Create an attribute collection from the element.
        Dim attrColl As XmlAttributeCollection = myElement.Attributes

        ' Show the collection by iterating over it.
        Console.WriteLine("Display all the attributes in the collection...")
        Dim i As Integer
        For i = 0 To attrColl.Count - 1
            Console.Write("{0} = ", attrColl.ItemOf(i).Name)
            Console.Write("{0}", attrColl.ItemOf(i).Value)
            Console.WriteLine()
        Next

        ' Retrieve a single attribute from the collection; specifically, the
        ' attribute with the name "misc".
        Dim attr As XmlAttribute = attrColl("misc")

        ' Retrieve the value from that attribute.
        Dim miscValue As String = attr.InnerXml

        Console.WriteLine("Display the attribute information.")
        Console.WriteLine(miscValue)

    End Sub
End Class
using System;
using System.IO;
using System.Xml;

public class Sample
{

    public static void Main()
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5' misc='sale item'>" +
                      "<title>The Handmaid's Tale</title>" +
                      "<price>14.95</price>" +
                      "</book>");

        // Move to an element.
        XmlElement myElement = doc.DocumentElement;

        // Create an attribute collection from the element.
        XmlAttributeCollection attrColl = myElement.Attributes;

        // Show the collection by iterating over it.
        Console.WriteLine("Display all the attributes in the collection...");
        for (int i = 0; i < attrColl.Count; i++)
        {
            Console.Write("{0} = ", attrColl[i].Name);
            Console.Write("{0}", attrColl[i].Value);
            Console.WriteLine();
        }

        // Retrieve a single attribute from the collection; specifically, the
        // attribute with the name "misc".
        XmlAttribute attr = attrColl["misc"];

        // Retrieve the value from that attribute.
        String miscValue = attr.InnerXml;

        Console.WriteLine("Display the attribute information.");
        Console.WriteLine(miscValue);

    }
}

W tym przykładzie zostaną wyświetlone następujące dane wyjściowe:

Wyjście

Wyświetl wszystkie atrybuty w kolekcji.

genre = novel
ISBN = 1-861001-57-5
misc = sale item
Display the attribute information.
sale item

Informacje w kolekcji atrybutów można pobrać według nazwy lub numeru indeksu. W powyższym przykładzie pokazano, jak pobrać dane według nazwy. W następnym przykładzie pokazano, jak pobrać dane według numeru indeksu.

Ponieważ element XmlAttributeCollection jest kolekcją i może być iterowany według nazwy lub indeksu, w tym przykładzie pokazano wybranie pierwszego atrybutu z kolekcji przy użyciu indeksu zero i użycie następującego pliku, baseuri.xml jako danych wejściowych.

Dane wejściowe

<!-- XML fragment -->
<book genre="novel">
  <title>Pride And Prejudice</title>
</book>
Option Explicit On
Option Strict On

Imports System.IO
Imports System.Xml

Public Class Sample

    Public Shared Sub Main()
        ' Create the XmlDocument.
        Dim doc As New XmlDocument()
        doc.Load("http://localhost/baseuri.xml")

        ' Display information on the attribute node. The value
        ' returned for BaseURI is 'http://localhost/baseuri.xml'.
        Dim attr As XmlAttribute = doc.DocumentElement.Attributes(0)
        Console.WriteLine("Name of the attribute:  {0}", attr.Name)
        Console.WriteLine("Base URI of the attribute:  {0}", attr.BaseURI)
        Console.WriteLine("The value of the attribute:  {0}", attr.InnerText)
    End Sub 'Main
End Class 'Sample
using System;
using System.IO;
using System.Xml;

public class Sample
{
  public static void Main()
  {
    // Create the XmlDocument.
    XmlDocument doc = new XmlDocument();

    doc.Load("http://localhost/baseuri.xml");

    // Display information on the attribute node. The value
    // returned for BaseURI is 'http://localhost/baseuri.xml'.
    XmlAttribute attr = doc.DocumentElement.Attributes[0];
    Console.WriteLine("Name of the attribute:  {0}", attr.Name);
    Console.WriteLine("Base URI of the attribute:  {0}", attr.BaseURI);
    Console.WriteLine("The value of the attribute:  {0}", attr.InnerText);
  }
}

Pobieranie pojedynczego węzła atrybutu

Aby pobrać jeden węzeł atrybutu z elementu, XmlElement.GetAttributeNode używana jest metoda . Zwraca obiekt typu XmlAttribute. Po utworzeniu atrybutu XmlAttribute wszystkie metody i właściwości dostępne w System.Xml.XmlAttribute klasie są dostępne w tym obiekcie, takie jak znalezienie elementu OwnerElement.

Imports System.IO
Imports System.Xml

Public Class Sample

    Public Shared Sub Main()

        Dim doc As XmlDocument = New XmlDocument()
        doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5' misc='sale item'>" & _
               "<title>The Handmaid's Tale</title>" & _
               "<price>14.95</price>" & _
               "</book>")

        ' Move to an element.
        Dim root As XmlElement
        root = doc.DocumentElement

        ' Get an attribute.
        Dim attr As XmlAttribute
        attr = root.GetAttributeNode("ISBN")

        ' Display the value of the attribute.
        Dim attrValue As String
        attrValue = attr.InnerXml
        Console.WriteLine(attrValue)

    End Sub
End Class
using System;
using System.IO;
using System.Xml;

 public class Sample
 {
      public static void Main()
      {
    XmlDocument doc = new XmlDocument();
     doc.LoadXml("<book genre='novel' ISBN='1-861003-78' misc='sale item'>" +
                   "<title>The Handmaid's Tale</title>" +
                   "<price>14.95</price>" +
                   "</book>");

    // Move to an element.
     XmlElement root = doc.DocumentElement;

    // Get an attribute.
     XmlAttribute attr = root.GetAttributeNode("ISBN");

    // Display the value of the attribute.
     String attrValue = attr.InnerXml;
     Console.WriteLine(attrValue);

    }
}

Można również zrobić to, jak pokazano w poprzednim przykładzie, gdzie z kolekcji atrybutów jest pobierany pojedynczy węzeł atrybutu. Poniższy przykład kodu pokazuje, jak można napisać jeden wiersz kodu w celu pobrania pojedynczego atrybutu według numeru indeksu z katalogu głównego drzewa dokumentów XML, znanego również jako właściwość DocumentElement .

XmlAttribute attr = doc.DocumentElement.Attributes[0];

Zobacz też