Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

Accessing Attributes in the DOM

Attributes are properties of the element, not children of the element. This distinction is important because of the methods used to navigate sibling, parent, and child nodes of the XML Document Object Model (DOM). For example, the PreviousSibling and NextSibling methods are not used to navigate from an element to an attribute or between attributes. Instead, an attribute is a property of an element and is owned by an element, has an OwnerElement property and not a parentNode property, and has distinct methods of navigation.

When the current node is an element, use the HasAttribute method to see if there are any attributes associated with the element. Once it is known that an element has attributes, there are multiple methods for accessing attributes. To retrieve a single attribute from the element, you can use the GetAttribute and GetAttributeNode methods of the XmlElement or you can obtain all the attributes into a collection. Obtaining the collection is useful if you need to iterate over the collection. If you want all attributes from the element, use the Attributes property of the element to retrieve all the attributes into a collection.

If you want all the attributes of an element node put into a collection, call the XmlElement.Attributes property. This gets the XmlAttributeCollection that contains all the attributes of an element. The XmlAttributeCollection class inherits from the XmlNamedNode map. Therefore, the methods and properties available on the collection include those available on a named node map in addition to methods and properties specific to the XmlAttributeCollection class, such as the ItemOf property or the Append method. Each item in the attribute collection represents an XmlAttribute node. To find the number of attributes on an element, get the XmlAttributeCollection, and use the Count property to see how many XmlAttribute nodes are in the collection.

The following code example shows how to retrieve an attribute collection and, using the Count method for the looping index, iterate over it. The code then shows how to retrieve a single attribute from the collection and display its value.

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

    }
}

This example displays the following output:

Output

Display all the attributes in the collection.

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

The information in an attribute collection can be retrieved by name or index number. The example above shows how to retrieve data by name. The next example shows how to retrieve data by index number.

Because the XmlAttributeCollection is a collection and can be iterated over by name or index, this example shows selecting the first attribute out of the collection using a zero-based index and using the following file, baseuri.xml, as input.

<!-- XML fragment -->
<book genre="novel">
  <title>Pride And Prejudice</title>
</book>
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 attribtue:  {0}", attr.InnerText);
  }
}

To retrieve a single attribute node from an element, the XmlElement.GetAttributeNode method is used. It returns an object of type XmlAttribute. Once you have an XmlAttribute, all the methods and properties available in the XmlAttribute Members class are available on that object, such as finding the OwnerElement.

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

    }
}

You can also do as shown in the previous example, where a single attribute node is retrieved from the attribute collection. The following code example shows how one line of code can be written to retrieve a single attribute by index number from the root of the XML document tree, also known as the DocumentElement property.

XmlAttribute attr = doc.DocumentElement.Attributes[0];
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.