Поделиться через


Доступ к атрибутам в DOM

Атрибуты — это свойства элемента, а не дочерние элементы элемента. Это различие важно из-за методов, используемых для перехода между братьями, родительскими и дочерними узлами объектной модели XML-документа (DOM). Например, методы PreviousSibling и NextSibling не используются для перехода от элемента к атрибуту или между атрибутами. Вместо этого атрибут является свойством элемента и принадлежит элементу, имеет свойство OwnerElement , а не свойство parentNode и имеет различные методы навигации.

Если текущий узел является элементом, используйте метод HasAttribute , чтобы узнать, есть ли какие-либо атрибуты, связанные с элементом. После того как известно, что элемент имеет атрибуты, существует несколько методов для доступа к атрибутам. Чтобы получить один атрибут из элемента, можно использовать методы GetAttribute и GetAttributeNodexmlElement или получить все атрибуты в коллекцию. Доступ к коллекции полезен, если необходимо произвести итерацию по ней. Чтобы получить все атрибуты из элемента, используйте свойство Attributes элемента, чтобы получить все атрибуты в коллекцию.

Получение всех атрибутов в коллекцию

Если требуется, чтобы все атрибуты узла элемента были помещены в коллекцию, вызовите свойство XmlElement.Attributes . Получает объект XmlAttributeCollection, содержащий все атрибуты элемента. Класс XmlAttributeCollection наследует от карты 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];

См. также