Mengakses Atribut di DOM

Atribut adalah properti elemen, bukan turunan dari elemen. Perbedaan ini penting karena metode yang digunakan untuk menavigasi simpul saudara kandung, induk, dan anak dari Model Objek Dokumen XML (DOM). Misalnya, metode PreviousSibling dan NextSibling tidak digunakan untuk menavigasi dari elemen ke atribut atau di antara atribut. Sebaliknya, atribut adalah properti dari elemen dan dimiliki oleh elemen, memiliki properti OwnerElement dan bukan properti parentNode, dan memiliki metode navigasi yang berbeda.

Ketika simpul saat ini adalah elemen, gunakan metode HasAttribute untuk melihat apakah ada atribut yang terkait dengan elemen. Setelah diketahui bahwa elemen memiliki atribut, ada beberapa metode untuk mengakses atribut. Untuk mengambil satu atribut dari elemen, Anda dapat menggunakan metode GetAttribute dan GetAttributeNode dari XmlElement atau Anda dapat memperoleh semua atribut ke dalam koleksi. Mendapatkan koleksi berguna jika Anda perlu melakukan iterasi atas koleksi. Jika Anda menginginkan semua atribut dari elemen, gunakan properti Atribut elemen untuk mengambil semua atribut ke dalam koleksi.

Mengambil Semua Atribut ke dalam Koleksi

Jika Anda ingin semua atribut simpul elemen dimasukkan ke dalam koleksi, panggil properti XmlElement.Attributes. Ini mendapatkan XmlAttributeCollection yang berisi semua atribut elemen. Kelas XmlAttributeCollection mewarisi dari peta XmlNamedNode . Oleh karena itu, metode dan properti yang tersedia pada koleksi mencakup yang tersedia pada peta simpul bernama selain metode dan properti khusus untuk kelas XmlAttributeCollection, seperti properti ItemOf atau metode Tambahkan. Setiap item dalam koleksi atribut mewakili simpul XmlAttribute. Untuk menemukan jumlah atribut pada elemen, dapatkan XmlAttributeCollection, dan gunakan properti Hitung untuk melihat berapa banyak simpul XmlAttribute dalam koleksi.

Contoh kode berikut menunjukkan cara mengambil koleksi atribut dan, menggunakan metode Hitung untuk indeks perulangan, melakukan iterasi di atasnya. Kode kemudian menunjukkan cara mengambil satu atribut dari koleksi dan menampilkan nilainya.

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

    }
}

Contoh ini menampilkan output berikut:

Hasil

Menampilkan semua atribut dalam koleksi.

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

Informasi dalam koleksi atribut dapat diambil berdasarkan nama atau nomor indeks. Contoh di atas menunjukkan cara mengambil data berdasarkan nama. Contoh berikutnya menunjukkan cara mengambil data menurut nomor indeks.

Karena XmlAttributeCollection adalah koleksi dan dapat diulang berdasarkan nama atau indeks, contoh ini menunjukkan pemilihan atribut pertama dari koleksi menggunakan indeks berbasis nol dan menggunakan file berikut, baseuri.xml, sebagai input.

Input

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

Mengambil Simpul Atribut Individu

Untuk mengambil simpul atribut tunggal dari elemen, XmlElement.GetAttributeNode metode ini digunakan. Ini mengembalikan objek jenis XmlAttribute. Setelah Anda memiliki XmlAttribute, semua metode dan properti yang tersedia di kelas tersedia pada objek tersebut System.Xml.XmlAttribute, seperti menemukan 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);

    }
}

Anda juga dapat melakukan seperti yang ditunjukkan pada contoh sebelumnya, di mana satu simpul atribut diambil dari koleksi atribut. Contoh kode berikut menunjukkan bagaimana satu baris kode dapat ditulis untuk mengambil atribut tunggal menurut nomor indeks dari akar pohon dokumen XML, juga dikenal sebagai properti DocumentElement.

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

Lihat juga