访问 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];

另请参阅