Reading Attributes

The XmlReader class provides various methods and properties for reading attributes. Attributes are most commonly found on elements. However, they are also allowed on XML declaration and document type nodes.

Reading Attributes on Elements

When positioned on an element node, the MoveToAttribute methods enable you to go through the attribute list of the element. After MoveToAttribute has been called, the node properties—such as Name, NamespaceURI, Prefix, and so on—reflect the properties of that attribute, and not the containing element it belongs to.

The following table describes the methods and properties that are designed specifically to process attributes.

Parses the attribute value into one or more Text, EntityReference, or EndEntity nodes.

Any of the general XmlReader methods and properties can also be used to process attributes. For example, after the XmlReader is positioned on an attribute, the Name and Value properties reflect the values of the attribute. You can also use any of the content Read methods to get the value of the attribute.

Reading Attributes on Other Node Types

Processing attributes on element nodes is the most common scenario. Attributes can also be found on XML Declarations and document type declarations.

Note

When the XmlReader is positioned on a processing instruction node, the Value property returns the entire text content. Items in the processing instruction node are not treated as attributes. They cannot be read with the GetAttribute or MoveToAttribute methods.

XML Declaration Node

When positioned on an XML Declaration node, the version, standalone, and encoding information are returned as a single string by the Value property. On some readers the version, encoding and stand-alone information can be also exposed as attributes.

Document Type Node

When the XmlReader is positioned on a Document Type node, the GetAttribute method and Item property can be used to return the values for the SYSTEM and PUBLIC literals. For example, calling reader.GetAttribute("PUBLIC") returns the PUBLIC value.

Examples

The following example reads all attributes on an element using the AttributeCount property.