DOM Özniteliklerine Erişim

Öznitelikler öğenin alt öğeleri değil, öğesinin özellikleridir. XML Belge Nesne Modeli'nin (DOM) eşdüzey, üst ve alt düğümlerinde gezinmek için kullanılan yöntemler nedeniyle bu ayrım önemlidir. Örneğin, PreviousSibling ve NextSibling yöntemleri bir öğeden bir özniteliğe veya öznitelikler arasında gezinmek için kullanılmaz. Bunun yerine, öznitelik bir öğenin özelliğidir ve bir öğeye aittir, parentNode özelliği değil OwnerElement özelliğine sahiptir ve ayrı gezinti yöntemlerine sahiptir.

Geçerli düğüm bir öğe olduğunda, öğesiyle ilişkilendirilmiş öznitelikler olup olmadığını görmek için HasAttribute yöntemini kullanın. Bir öğenin öznitelikleri olduğu bilindikten sonra, özniteliklere erişmek için birden çok yöntem vardır. öğesinden tek bir öznitelik almak için XmlElement'in GetAttribute ve GetAttributeNode yöntemlerini kullanabilir veya tüm öznitelikleri bir koleksiyona alabilirsiniz. Koleksiyonun alınması, koleksiyon üzerinde yinelemeniz gerekiyorsa kullanışlıdır. öğesindeki tüm öznitelikleri istiyorsanız, öğesinin Attributes özelliğini kullanarak tüm öznitelikleri bir koleksiyona alın.

Koleksiyona Tüm Öznitelikleri Alma

Bir öğe düğümünün tüm özniteliklerinin bir koleksiyona konulmasını istiyorsanız, XmlElement.Attributes özelliğini çağırın. Bu, bir öğenin tüm özniteliklerini içeren XmlAttributeCollection'ı alır. XmlAttributeCollection sınıfı XmlNamedNode eşlemesinden devralır. Bu nedenle, koleksiyonda kullanılabilen yöntemler ve özellikler, ItemOf özelliği veya Append yöntemi gibi XmlAttributeCollection sınıfına özgü yöntemlere ve özelliklere ek olarak adlandırılmış düğüm eşlemesinde bulunanları içerir. Öznitelik koleksiyonundaki her öğe bir XmlAttribute düğümünü temsil eder. Bir öğedeki öznitelik sayısını bulmak için XmlAttributeCollection değerini alın ve Count özelliğini kullanarak koleksiyonda kaç XmlAttribute düğümü olduğunu görün.

Aşağıdaki kod örneği, bir öznitelik koleksiyonunun nasıl alınıp döngü dizini için Count yöntemini kullanarak bunun üzerinde yineleme yapılacağını gösterir. Kod daha sonra koleksiyondan tek bir özniteliğin nasıl alınıp değerinin görüntüleneceğini gösterir.

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

    }
}

Bu örnekte aşağıdaki çıkış görüntülenir:

Çıktı

Koleksiyondaki tüm öznitelikleri görüntüleyin.

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

Öznitelik koleksiyonundaki bilgiler ad veya dizin numarasına göre alınabilir. Yukarıdaki örnekte verilerin ada göre nasıl alındığı gösterilmektedir. Sonraki örnekte dizin numarasına göre verilerin nasıl alındığı gösterilmektedir.

XmlAttributeCollection bir koleksiyon olduğundan ve ada veya dizine göre yinelenebilir, bu örnekte sıfır tabanlı dizin kullanarak koleksiyondaki ilk özniteliğin seçilmesi ve giriş olarak baseuri.xml aşağıdaki dosyanın kullanılması gösterilir.

Giriş

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

Tek Bir Öznitelik Düğümünü Alma

Bir öğeden XmlElement.GetAttributeNode tek bir öznitelik düğümü almak için yöntemi kullanılır. XmlAttribute türünde bir nesne döndürür. XmlAttribute'a sahip olduktan sonra, sınıfında kullanılabilen System.Xml.XmlAttribute tüm yöntemler ve özellikler, OwnerElement'i bulma gibi bu nesnede kullanılabilir.

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

    }
}

Ayrıca, öznitelik koleksiyonundan tek bir öznitelik düğümünü alınan önceki örnekte gösterildiği gibi de yapabilirsiniz. Aşağıdaki kod örneğinde, DOCUMENTElement özelliği olarak da bilinen XML belge ağacının kökünden dizin numarasına göre tek bir özniteliği almak için bir kod satırının nasıl yazılacağı gösterilmektedir.

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

Ayrıca bkz.