共用方式為


存取 DOM 中的屬性

屬性是元素的屬性,而不是元素的子系。 這項區別很重要,因為用來巡覽 XML 文件物件模型(DOM)之同層級、父節點和子節點的方法。 例如,PreviousSiblingNextSibling 方法不會用來從元素巡覽至屬性或屬性之間。 相反地,屬性是元素本身的特徵,並由元素擁有,有 OwnerElement 屬性而非 parentNode 屬性,且具備不同的導覽方法。

當目前的節點是元素時,請使用 HasAttribute 方法來查看是否有任何與 專案相關聯的屬性。 一旦知道元素具有屬性,就會有多個方法來存取屬性。 若要從 專案擷取單一屬性,您可以使用 XmlElementGetAttribute 和GetAttributeNode 方法,也可以取得集合中的所有屬性。 如果您需要遍歷這個集合,那麼取得集合會很有用。 如果您想要來自 專案的所有屬性,請使用 專案的 Attributes 屬性,將所有屬性擷取到集合中。

將所有屬性擷取至集合

如果您想要將項目節點的所有屬性放入集合中,請呼叫 XmlElement.Attributes 屬性。 這會取得包含專案所有屬性的 XmlAttributeCollectionXmlAttributeCollection 類別繼承自 XmlNamedNode 映射。 因此,除了 XmlAttributeCollection 類別特有的方法和屬性,例如 ItemOf 屬性或 Append 方法之外,集合中可用的方法和屬性還包括在具名節點對應上提供的方法和屬性。 屬性集合中的每個專案都代表 XmlAttribute 節點。 若要尋找元素上的屬性數目,請取得 XmlAttributeCollection,並使用 Count 屬性查看集合中的 XmlAttribute 節點數目。

下列程式代碼範例示範如何擷取屬性集合,並使用迴圈索引的 Count 方法逐一查看。 然後,程式代碼會示範如何從集合擷取單一屬性,並顯示其值。

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

    }
}

這個範例會顯示下列輸出:

輸出

顯示集合中的所有屬性。

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

屬性集合中的資訊可以依名稱或索引編號擷取。 上述範例示範如何依名稱擷取數據。 下一個範例示範如何依索引編號擷取數據。

因為 XmlAttributeCollection 是一個集合,而且可以依名稱或索引逐一查看,所以此範例示範使用以零起始的索引選取集合中的第一個屬性,並使用下列檔案 ,baseuri.xml做為輸入。

輸入

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

擷取單一屬性節點

若要從元素擷取單一屬性節點,則會使用 XmlElement.GetAttributeNode 方法。 它會傳回 XmlAttribute 類型的物件。 一旦您有 XmlAttribute,類別中 System.Xml.XmlAttribute 可用的所有方法和屬性都可以在該物件上使用,例如尋找 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);

    }
}

您也可以如上一個範例所示執行,其中會從屬性集合擷取單一屬性節點。 下列程式代碼範例示範如何撰寫一行程序代碼,以依 XML 檔案樹根目錄的索引編號擷取單一屬性,也稱為 DocumentElement 屬性。

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

另請參閱