Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

XmlReader Class

Represents a reader that provides fast, noncached, forward-only access to XML data.

To browse the .NET Framework source code for this type, see the Reference Source.

Namespace:  System.Xml
Assemblies:   System.Xml (in System.Xml.dll)
  System.Xml.ReaderWriter (in System.Xml.ReaderWriter.dll)

[DebuggerDisplayAttribute("{debuggerDisplayProxy}")]
[DebuggerDisplayAttribute("{debuggerDisplayProxy}")]
public abstract class XmlReader : IDisposable

The XmlReader type exposes the following members.

  NameDescription
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibraryXmlReaderInitializes a new instance of the XmlReader class.
Top

  NameDescription
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryAttributeCountWhen overridden in a derived class, gets the number of attributes on the current node.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryBaseURIWhen overridden in a derived class, gets the base URI of the current node.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryCanReadBinaryContentGets a value indicating whether the XmlReader implements the binary content read methods.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryCanReadValueChunkGets a value indicating whether the XmlReader implements the ReadValueChunk method.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryCanResolveEntityGets a value indicating whether this reader can parse and resolve entities.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryDepthWhen overridden in a derived class, gets the depth of the current node in the XML document.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryEOFWhen overridden in a derived class, gets a value indicating whether the reader is positioned at the end of the stream.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryHasAttributesGets a value indicating whether the current node has any attributes.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryHasValueWhen overridden in a derived class, gets a value indicating whether the current node can have a Value.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryIsDefaultWhen overridden in a derived class, gets a value indicating whether the current node is an attribute that was generated from the default value defined in the DTD or schema.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryIsEmptyElementWhen overridden in a derived class, gets a value indicating whether the current node is an empty element (for example, <MyElement/>).
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryItem[Int32]When overridden in a derived class, gets the value of the attribute with the specified index.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryItem[String]When overridden in a derived class, gets the value of the attribute with the specified Name.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryItem[String, String]When overridden in a derived class, gets the value of the attribute with the specified LocalName and NamespaceURI.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryLocalNameWhen overridden in a derived class, gets the local name of the current node.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryNameWhen overridden in a derived class, gets the qualified name of the current node.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryNamespaceURIWhen overridden in a derived class, gets the namespace URI (as defined in the W3C Namespace specification) of the node on which the reader is positioned.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryNameTableWhen overridden in a derived class, gets the XmlNameTable associated with this implementation.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryNodeTypeWhen overridden in a derived class, gets the type of the current node.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryPrefixWhen overridden in a derived class, gets the namespace prefix associated with the current node.
Public propertySupported by the XNA FrameworkQuoteCharWhen overridden in a derived class, gets the quotation mark character used to enclose the value of an attribute node.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryReadStateWhen overridden in a derived class, gets the state of the reader.
Public propertySupported by the XNA FrameworkSchemaInfoGets the schema information that has been assigned to the current node as a result of schema validation.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySettingsGets the XmlReaderSettings object used to create this XmlReader instance.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryValueWhen overridden in a derived class, gets the text value of the current node.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryValueTypeGets The Common Language Runtime (CLR) type for the current node.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryXmlLangWhen overridden in a derived class, gets the current xml:lang scope.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryXmlSpaceWhen overridden in a derived class, gets the current xml:space scope.
Top

  NameDescription
Public methodSupported by the XNA FrameworkCloseWhen overridden in a derived class, changes the ReadState to Closed.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryCreate(Stream)Creates a new XmlReader instance using the specified stream with default settings.
Public methodStatic memberSupported by the XNA FrameworkCreate(String)Creates a new XmlReader instance with specified URI.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryCreate(TextReader)Creates a new XmlReader instance by using the specified text reader.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryCreate(Stream, XmlReaderSettings)Creates a new XmlReader instance with the specified stream and settings.
Public methodStatic memberSupported by the XNA FrameworkCreate(String, XmlReaderSettings)Creates a new XmlReader instance by using the specified URI and settings.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryCreate(TextReader, XmlReaderSettings)Creates a new XmlReader instance by using the specified text reader and settings.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryCreate(XmlReader, XmlReaderSettings)Creates a new XmlReader instance by using the specified XML reader and settings.
Public methodStatic memberSupported by the XNA FrameworkCreate(Stream, XmlReaderSettings, String)Creates a new XmlReader instance using the specified stream, base URI, and settings.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryCreate(Stream, XmlReaderSettings, XmlParserContext)Creates a new XmlReader instance using the specified stream, settings, and context information for parsing.
Public methodStatic memberSupported by the XNA FrameworkCreate(String, XmlReaderSettings, XmlParserContext)Creates a new XmlReader instance by using the specified URI, settings, and context information for parsing.
Public methodStatic memberSupported by the XNA FrameworkCreate(TextReader, XmlReaderSettings, String)Creates a new XmlReader instance by using the specified text reader, settings, and base URI.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryCreate(TextReader, XmlReaderSettings, XmlParserContext)Creates a new XmlReader instance by using the specified text reader, settings, and context information for parsing.
Public methodSupported by Portable Class LibraryDispose()Releases all resources used by the current instance of the XmlReader class.
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibraryDispose(Boolean)Releases the unmanaged resources used by the XmlReader and optionally releases the managed resources.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibraryFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryGetAttribute(Int32)When overridden in a derived class, gets the value of the attribute with the specified index.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryGetAttribute(String)When overridden in a derived class, gets the value of the attribute with the specified Name.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryGetAttribute(String, String)When overridden in a derived class, gets the value of the attribute with the specified LocalName and NamespaceURI.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodGetValueAsyncAsynchronously gets the value of the current node.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryIsNameReturns a value indicating whether the string argument is a valid XML name.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryIsNameTokenReturns a value indicating whether or not the string argument is a valid XML name token.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryIsStartElement()Calls MoveToContent and tests if the current content node is a start tag or empty element tag.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryIsStartElement(String)Calls MoveToContent and tests if the current content node is a start tag or empty element tag and if the Name property of the element found matches the given argument.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryIsStartElement(String, String)Calls MoveToContent and tests if the current content node is a start tag or empty element tag and if the LocalName and NamespaceURI properties of the element found match the given strings.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryLookupNamespaceWhen overridden in a derived class, resolves a namespace prefix in the current element's scope.
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibraryMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryMoveToAttribute(Int32)When overridden in a derived class, moves to the attribute with the specified index.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryMoveToAttribute(String)When overridden in a derived class, moves to the attribute with the specified Name.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryMoveToAttribute(String, String)When overridden in a derived class, moves to the attribute with the specified LocalName and NamespaceURI.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryMoveToContentChecks whether the current node is a content (non-white space text, CDATA, Element, EndElement, EntityReference, or EndEntity) node. If the node is not a content node, the reader skips ahead to the next content node or end of file. It skips over nodes of the following type: ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace.
Public methodMoveToContentAsyncAsynchronously checks whether the current node is a content node. If the node is not a content node, the reader skips ahead to the next content node or end of file.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryMoveToElementWhen overridden in a derived class, moves to the element that contains the current attribute node.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryMoveToFirstAttributeWhen overridden in a derived class, moves to the first attribute.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryMoveToNextAttributeWhen overridden in a derived class, moves to the next attribute.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadWhen overridden in a derived class, reads the next node from the stream.
Public methodReadAsyncAsynchronously reads the next node from the stream.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadAttributeValueWhen overridden in a derived class, parses the attribute value into one or more Text, EntityReference, or EndEntity nodes.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadContentAsReads the content as an object of the type specified.
Public methodReadContentAsAsyncAsynchronously reads the content as an object of the type specified.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadContentAsBase64Reads the content and returns the Base64 decoded binary bytes.
Public methodReadContentAsBase64AsyncAsynchronously reads the content and returns the Base64 decoded binary bytes.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadContentAsBinHexReads the content and returns the BinHex decoded binary bytes.
Public methodReadContentAsBinHexAsyncAsynchronously reads the content and returns the BinHex decoded binary bytes.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadContentAsBooleanReads the text content at the current position as a Boolean.
Public methodSupported by the XNA FrameworkReadContentAsDateTimeReads the text content at the current position as a DateTime object.
Public methodReadContentAsDateTimeOffsetReads the text content at the current position as a DateTimeOffset object.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadContentAsDecimalReads the text content at the current position as a Decimal object.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadContentAsDoubleReads the text content at the current position as a double-precision floating-point number.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadContentAsFloatReads the text content at the current position as a single-precision floating point number.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadContentAsIntReads the text content at the current position as a 32-bit signed integer.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadContentAsLongReads the text content at the current position as a 64-bit signed integer.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadContentAsObjectReads the text content at the current position as an Object.
Public methodReadContentAsObjectAsyncAsynchronously reads the text content at the current position as an Object.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadContentAsStringReads the text content at the current position as a String object.
Public methodReadContentAsStringAsyncAsynchronously reads the text content at the current position as a String object.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadElementContentAs(Type, IXmlNamespaceResolver)Reads the element content as the requested type.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadElementContentAs(Type, IXmlNamespaceResolver, String, String)Checks that the specified local name and namespace URI matches that of the current element, then reads the element content as the requested type.
Public methodReadElementContentAsAsyncAsynchronously reads the element content as the requested type.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadElementContentAsBase64Reads the element and decodes the Base64 content.
Public methodReadElementContentAsBase64AsyncAsynchronously reads the element and decodes the Base64 content.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadElementContentAsBinHexReads the element and decodes the BinHex content.
Public methodReadElementContentAsBinHexAsyncAsynchronously reads the element and decodes the BinHex content.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadElementContentAsBoolean()Reads the current element and returns the contents as a Boolean object.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadElementContentAsBoolean(String, String)Checks that the specified local name and namespace URI matches that of the current element, then reads the current element and returns the contents as a Boolean object.
Public methodSupported by the XNA FrameworkReadElementContentAsDateTime()Reads the current element and returns the contents as a DateTime object.
Public methodSupported by the XNA FrameworkReadElementContentAsDateTime(String, String)Checks that the specified local name and namespace URI matches that of the current element, then reads the current element and returns the contents as a DateTime object.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadElementContentAsDecimal()Reads the current element and returns the contents as a Decimal object.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadElementContentAsDecimal(String, String)Checks that the specified local name and namespace URI matches that of the current element, then reads the current element and returns the contents as a Decimal object.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadElementContentAsDouble()Reads the current element and returns the contents as a double-precision floating-point number.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadElementContentAsDouble(String, String)Checks that the specified local name and namespace URI matches that of the current element, then reads the current element and returns the contents as a double-precision floating-point number.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadElementContentAsFloat()Reads the current element and returns the contents as single-precision floating-point number.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadElementContentAsFloat(String, String)Checks that the specified local name and namespace URI matches that of the current element, then reads the current element and returns the contents as a single-precision floating-point number.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadElementContentAsInt()Reads the current element and returns the contents as a 32-bit signed integer.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadElementContentAsInt(String, String)Checks that the specified local name and namespace URI matches that of the current element, then reads the current element and returns the contents as a 32-bit signed integer.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadElementContentAsLong()Reads the current element and returns the contents as a 64-bit signed integer.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadElementContentAsLong(String, String)Checks that the specified local name and namespace URI matches that of the current element, then reads the current element and returns the contents as a 64-bit signed integer.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadElementContentAsObject()Reads the current element and returns the contents as an Object.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadElementContentAsObject(String, String)Checks that the specified local name and namespace URI matches that of the current element, then reads the current element and returns the contents as an Object.
Public methodReadElementContentAsObjectAsyncAsynchronously reads the current element and returns the contents as an Object.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadElementContentAsString()Reads the current element and returns the contents as a String object.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadElementContentAsString(String, String)Checks that the specified local name and namespace URI matches that of the current element, then reads the current element and returns the contents as a String object.
Public methodReadElementContentAsStringAsyncAsynchronously reads the current element and returns the contents as a String object.
Public methodSupported by the XNA FrameworkReadElementString()Reads a text-only element. However, we recommend that you use the ReadElementContentAsString() method instead, because it provides a more straightforward way to handle this operation.
Public methodSupported by the XNA FrameworkReadElementString(String)Checks that the Name property of the element found matches the given string before reading a text-only element. However, we recommend that you use the ReadElementContentAsString() method instead, because it provides a more straightforward way to handle this operation.
Public methodSupported by the XNA FrameworkReadElementString(String, String)Checks that the LocalName and NamespaceURI properties of the element found matches the given strings before reading a text-only element. However, we recommend that you use the ReadElementContentAsString(String, String) method instead, because it provides a more straightforward way to handle this operation.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadEndElementChecks that the current content node is an end tag and advances the reader to the next node.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadInnerXmlWhen overridden in a derived class, reads all the content, including markup, as a string.
Public methodReadInnerXmlAsyncAsynchronously reads all the content, including markup, as a string.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadOuterXmlWhen overridden in a derived class, reads the content, including markup, representing this node and all its children.
Public methodReadOuterXmlAsyncAsynchronously reads the content, including markup, representing this node and all its children.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadStartElement()Checks that the current node is an element and advances the reader to the next node.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadStartElement(String)Checks that the current content node is an element with the given Name and advances the reader to the next node.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadStartElement(String, String)Checks that the current content node is an element with the given LocalName and NamespaceURI and advances the reader to the next node.
Public methodSupported by the XNA FrameworkReadStringWhen overridden in a derived class, reads the contents of an element or text node as a string. However, we recommend that you use the ReadElementContentAsString method instead, because it provides a more straightforward way to handle this operation.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadSubtreeReturns a new XmlReader instance that can be used to read the current node, and all its descendants.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadToDescendant(String)Advances the XmlReader to the next descendant element with the specified qualified name.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadToDescendant(String, String)Advances the XmlReader to the next descendant element with the specified local name and namespace URI.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadToFollowing(String)Reads until an element with the specified qualified name is found.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadToFollowing(String, String)Reads until an element with the specified local name and namespace URI is found.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadToNextSibling(String)Advances the XmlReader to the next sibling element with the specified qualified name.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadToNextSibling(String, String)Advances the XmlReader to the next sibling element with the specified local name and namespace URI.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryReadValueChunkReads large streams of text embedded in an XML document.
Public methodReadValueChunkAsyncAsynchronously reads large streams of text embedded in an XML document.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryResolveEntityWhen overridden in a derived class, resolves the entity reference for EntityReference nodes.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySkipSkips the children of the current node.
Public methodSkipAsyncAsynchronously skips the children of the current node.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryToStringReturns a string that represents the current object. (Inherited from Object.)
Top

  NameDescription
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIDisposable.DisposeFor a description of this member, see IDisposable.Dispose.
Top

NoteNote

To view the .NET Framework source code for this type, see the Reference Source. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructions.

XmlReader provides forward-only, read-only access to XML data in a document or stream. This class conforms to the W3C Extensible Markup Language (XML) 1.0 (fourth edition) and the Namespaces in XML 1.0 (third edition) recommendations.

XmlReader methods let you move through XML data and read the contents of a node. The properties of the class reflect the value of the current node, which is where the reader is positioned. The ReadState property value indicates the current state of the XML reader. For example, the property is set to Initial by the XmlReader.Read method and Closed by the XmlReader.Close method. XmlReader also provides data conformance checks and validation against a DTD or schema.

XmlReader uses a pull model to retrieve data. This model:

  • Simplifies state management by a natural, top-down procedural refinement.

  • Supports multiple input streams and layering.

  • Enables the client to give the parser a buffer into which the string is directly written, and thus avoids the necessity of an extra string copy.

  • Supports selective processing. The client can skip items and process those that are of interest to the application. You can also set properties in advance to manage how the XML stream is processed (for example, normalization).

In this section:

Creating an XML reader
Validating XML data
Data conformance
Navigating through nodes
Reading XML elements
Reading XML attributes
Reading XML content
Converting to CLR types
Asynchronous programming
Security considerations

Creating an XML reader

Use the Create method to create an XmlReader instance.

Although the .NET Framework provides concrete implementations of the XmlReader class, such as the XmlTextReader, XmlNodeReader, and the XmlValidatingReader classes, we recommend that you use the specialized classes only in these scenarios:

  • When you want to read an XML DOM subtree from an XmlNode object, use the XmlNodeReader class. (However, this class doesn't support DTD or schema validation.)

  • If you must expand entities on request, you don't want your text content normalized, or you don't want default attributes returned, use the XmlTextReader class.

To specify the set of features you want to enable on the XML reader, pass an System.Xml.XmlReaderSettings object to the Create method. You can use a single System.Xml.XmlReaderSettings object to create multiple readers with the same functionality, or modify the System.Xml.XmlReaderSettings object to create a new reader with a different set of features. You can also easily add features to an existing reader.

If you don't use a System.Xml.XmlReaderSettings object, default settings are used. See the Create reference page for details.

XmlReader throws an XmlException on XML parse errors. After an exception is thrown, the state of the reader is not predictable. For example, the reported node type may be different from the actual node type of the current node. Use the ReadState property to check whether the reader is in error state.

Validating XML data

To define the structure of an XML document and its element relationships, data types, and content constraints, you use a document type definition (DTD) or XML Schema definition language (XSD) schema. An XML document is considered to be well formed if it meets all the syntactical requirements defined by the W3C XML 1.0 Recommendation. It's considered valid if it's well formed and also conforms to the constraints defined by its DTD or schema. (See the W3C XML Schema Part 1: Structures and the W3C XML Schema Part 2: Datatypes recommendations.) Therefore, although all valid XML documents are well formed, not all well-formed XML documents are valid.

You can validate the data against a DTD, an inline XSD Schema, or an XSD Schema stored in an XmlSchemaSet object (a cache); these scenarios are described on the Create reference page. XmlReader doesn't support XML-Data Reduced (XDR) schema validation.

You use the following settings on the XmlReaderSettings class to specify what type of validation, if any, the XmlReader instance supports.

Use this XmlReaderSettings member

To specify

DtdProcessing property

Whether to allow DTD processing. The default is to disallow DTD processing.

ValidationType property

Whether the reader should validate data, and what type of validation to perform (DTD or schema). The default is no data validation.

ValidationEventHandler event

An event handler for receiving information about validation events. If an event handler is not provided, an XmlException is thrown on the first validation error.

ValidationFlags property

Additional validation options through the XmlSchemaValidationFlags enumeration members:

  • AllowXmlAttributes -- Allow XML attributes (xml:*) in instance documents even when they're not defined in the schema. The attributes are validated based on their data type. See the XmlSchemaValidationFlags reference page for the setting to use in specific scenarios. (Disabled by default.)

  • ProcessIdentityConstraints -- Process identity constraints (xs:ID, xs:IDREF, xs:key, xs:keyref, xs:unique) encountered during validation. (Enabled by default.)

  • ProcessSchemaLocation -- Process schemas specified by the xsi:schemaLocation or xsi:noNamespaceSchemaLocation attribute. (Enabled by default.)

  • ProcessInlineSchema -- Process inline XML Schemas during validation. (Disabled by default.)

  • ReportValidationWarnings -- Report events if a validation warning occurs. A warning is typically issued when there is no DTD or XML Schema to validate a particular element or attribute against. The ValidationEventHandler is used for notification. (Disabled by default.)

Schemas

The XmlSchemaSet to use for validation.

XmlResolver property

The XmlResolver for resolving and accessing external resources. This can include external entities such as DTD and schemas, and any xs:include or xs:import elements contained in the XML Schema. If you don't specify an XmlResolver, the XmlReader uses a default XmlUrlResolver with no user credentials.

Data conformance

XML readers that are created by the Create method meet the following compliance requirements by default:

  • New lines and attribute value are normalized according to the W3C XML 1.0 Recommendation.

  • All entities are automatically expanded.

  • Default attributes declared in the document type definition are always added even when the reader doesn't validate.

  • Declaration of XML prefix mapped to the correct XML namespace URI is allowed.

  • The notation names in a single NotationType attribute declaration and NmTokens in a single Enumeration attribute declaration are distinct.

Use these XmlReaderSettings properties to specify the type of conformance checks you want to enable:

Use this XmlReaderSettings property

To

Default

CheckCharacters property

Enable or disable checks for the following:

  • Characters are within the range of legal XML characters, as defined by the 2.2 Characters section of the W3C XML 1.0 Recommendation.

  • All XML names are valid, as defined by the 2.3 Common Syntactic Constructs section of the W3C XML 1.0 Recommendation.

When this property is set to true (default), an XmlException exception is thrown if the XML file contains illegal characters or invalid XML names (for example, an element name starts with a number).

Character and name checking is enabled.

Setting CheckCharacters to false turns off character checking for character entity references. If the reader is processing text data, it always checks that XML names are valid, regardless of this setting.

NoteNote

The XML 1.0 recommendation requires document-level conformance when a DTD is present. Therefore, if the reader is configured to support ConformanceLevel.Fragment, but the XML data contains a document type definition (DTD), an XmlException is thrown.

ConformanceLevel property

Choose the level of conformance to enforce:

If the data isn't in conformance, an XmlException exception is thrown.

Document

Navigating through nodes

The current node is the XML node on which the XML reader is currently positioned. All XmlReader methods perform operations in relation to this node, and all XmlReader properties reflect the value of the current node.

The following methods make it easy to navigate through nodes and parse data.

Use this XmlReaderSettings method

To

Read

Read the first node, and advance through the stream one node at a time. Such calls are typically performed inside a while loop.

Use the NodeType property to get the type (for example, attribute, comment, element, and so on) of the current node.

Skip

Skip the children of the current node and move to the next node.

MoveToContent and MoveToContentAsync

Skip non-content nodes and move to the next content node or to the end of the file.

Non-content nodes include ProcessingInstruction, DocumentType, Comment, Whitespace, and SignificantWhitespace.

Content nodes include non-white space text, CDATA, EntityReference , and EndEntity.

ReadSubtree

Read an element and all its children, and return a new XmlReader instance set to ReadState.Initial.

This method is useful for creating boundaries around XML elements; for example, if you want to pass data to another component for processing and you want to limit how much of your data the component can access.

See the XmlReader.Read reference page for an example of navigating through a text stream one node at a time and displaying the type of each node.

The following sections describe how you can read specific types of data, such as elements, attributes, and typed data.

Reading XML elements

The following table lists the methods and properties that the XmlReader class provides for processing elements. After the XmlReader is positioned on an element, the node properties, such as Name, reflect the element values. In addition to the members described below, any of the general methods and properties of the XmlReader class can also be used to process elements. For example, you can use the ReadInnerXml method to read the contents of an element.

NoteNote

See section 3.1 of the W3C XML 1.0 Recommendation for definitions of start tags, end tags, and empty element tags.

Use this XmlReader member

To

IsStartElement method

Check if the current node is a start tag or an empty element tag.

ReadStartElement method

Check that the current node is an element and advance the reader to the next node (calls IsStartElement followed by Read).

ReadEndElement method

Check that the current node is an end tag and advance the reader to the next node.

ReadElementString method

Read a text-only element.

ReadToDescendant method

Advance the XML reader to the next descendant (child) element that has the specified name.

ReadToNextSibling method

Advance the XML reader to the next sibling element that has the specified name.

IsEmptyElement property

Check if the current element has an end element tag. For example:

For an example of reading the text content of elements, see the ReadString method. The following example processes elements by using a while loop.

while (reader.Read()) {
  if (reader.IsStartElement()) {
    if (reader.IsEmptyElement)
      Console.WriteLine("<{0}/>", reader.Name);
    else {
      Console.Write("<{0}> ", reader.Name);
      reader.Read(); // Read the start tag. 
      if (reader.IsStartElement())  // Handle nested elements.
        Console.Write("\r\n<{0}>", reader.Name);
      Console.WriteLine(reader.ReadString());  //Read the text content of the element.
    }
  } 
} 

Reading XML attributes

XML attributes are most commonly found on elements, but they're also allowed on XML declaration and document type nodes.

When positioned on an element node, the MoveToAttribute method lets you go through the attribute list of the element. Note that after MoveToAttribute has been called, node properties such as Name, NamespaceURI, and Prefix reflect the properties of that attribute, not the properties of the element the attribute belongs to.

The XmlReader class provides these methods and properties to read and process attributes on elements.

Use this XmlReader member

To

HasAttributes property

Check whether the current node has any attributes.

AttributeCount property

Get the number of attributes on the current element.

MoveToFirstAttribute method

Move to the first attribute in an element.

MoveToNextAttribute method

Move to the next attribute in an element.

MoveToAttribute method

Move to a specified attribute.

GetAttribute method or Item property

Get the value of a specified attribute.

IsDefault property

Check whether the current node is an attribute that was generated from the default value defined in the DTD or schema.

MoveToElement method

Move to the element that owns the current attribute. Use this method to return to an element after navigating through its attributes.

ReadAttributeValue method

Parse 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.

This example uses the AttributeCount property to navigate through all the attributes on an element.

// Display all attributes. 
if (reader.HasAttributes) {
  Console.WriteLine("Attributes of <" + reader.Name + ">");
  for (int i = 0; i < reader.AttributeCount; i++) {
    Console.WriteLine("  {0}", reader[i]);
  }
  // Move the reader back to the element node.
  reader.MoveToElement(); 
}

This example uses the MoveToNextAttribute method in a while loop to navigate through the attributes.

if (reader.HasAttributes) {
  Console.WriteLine("Attributes of <" + reader.Name + ">");
  while (reader.MoveToNextAttribute()) {
    Console.WriteLine(" {0}={1}", reader.Name, reader.Value);
  }
  // Move the reader back to the element node.
  reader.MoveToElement();
}

Reading attributes on XML declaration nodes

When the XML reader is positioned on an XML declaration node, the Value property returns the version, standalone, and encoding information as a single string. XmlReader objects created by the Create method, the XmlTextReader class, and the XmlValidatingReader class expose the version, standalone, and encoding items as attributes.

Reading attributes on document type nodes

When the XML reader 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.

Reading attributes on processing instruction nodes

When the XmlReader is positioned on a processing instruction node, the Value property returns the entire text content. Items in the processing instruction node aren't treated as attributes. They can't be read with the GetAttribute or MoveToAttribute method.

Reading XML content

The XMLReader class includes the following members that read content from an XML file and return the content as string values. (To return CLR types, see the next section.)

Use this XmlReader member

To

Value property

Get the text content of the current node. The value returned depends on the node type; see the Value reference page for details.

ReadString method

Get the content of an element or text node as a string. This method stops on processing instructions and comments.

For details on how this method handles specific node types, see the ReadString reference page.

ReadInnerXml and ReadInnerXmlAsync methods

Get all the content of the current node, including the markup, but excluding start and end tags. For example, for:

<node>this<child id="123"/></node>

ReadInnerXml returns:

this<child id="123"/>

ReadOuterXml and ReadOuterXmlAsync methods

Get all the content of the current node and its children, including markup and start/end tags. For example, for:

<node>this<child id="123"/></node>

ReadOuterXml returns:

<node>this<child id="123"/></node>

Converting to CLR types

You can use the members of the XmlReader class (listed in the following table) to read XML data and return values as common language runtime (CLR) types instead of strings. These members enable you to get values in the representation that is most appropriate for your coding task without having to manually parse or convert string values.

  • The ReadElementContentAs methods can only be called on element node types. These methods cannot be used on elements that contain child elements or mixed content. When called, the XmlReader object reads the start tag, reads the element content, and then moves past the end element tag. Processing instructions and comments are ignored and entities are expanded.

  • The ReadContentAs methods read the text content at the current reader position, and if the XML data doesn't have any schema or data type information associated with it, convert the text content to the requested return type. Text, white space, significant white space and CDATA sections are concatenated. Comments and processing instructions are skipped, and entity references are automatically resolved.

The XmlReader class uses the rules defined by the W3C XML Schema Part 2: Datatypes recommendation.

If an element can't easily be converted to a CLR type because of its format, you can use a schema mapping to ensure a successful conversion. The following example uses an .xsd file to convert the hire-date element to the xs:date type, and then uses the ReadElementContentAsDateTime method to return the element as a DateTime object.

Input (hireDate.xml):

<employee xmlns="urn:empl-hire">
    <ID>12365</ID>
    <hire-date>2003-01-08</hire-date>
    <title>Accountant</title>
</employee>

Schema (hireDate.xsd):

<?xml version="1.0"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="urn:empl-hire" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="employee">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="ID" type="xs:unsignedShort" />
        <xs:element name="hire-date" type="xs:date" />
        <xs:element name="title" type="xs:string" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Code:

// Create a validating XmlReader object. The schema  
// provides the necessary type information.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add("urn:empl-hire", "hireDate.xsd");
using (XmlReader reader = XmlReader.Create("hireDate.xml", settings)) {

  // Move to the hire-date element.
  reader.MoveToContent();
  reader.ReadToDescendant("hire-date");

  // Return the hire-date as a DateTime object.
  DateTime hireDate = reader.ReadElementContentAsDateTime();
  Console.WriteLine("Six Month Review Date: {0}", hireDate.AddMonths(6));
}

Output:

Six Month Review Date:  7/8/2003 12:00:00 AM

Asynchronous programming

Most of the XmlReader methods have asynchronous counterparts that have "Async" at the end of their method names. For example, the asynchronous equivalent of ReadContentAsObject is ReadContentAsObjectAsync.

The following methods can be used with asynchronous method calls:

The following sections describe asynchronous usage for methods that don't have asynchronous counterparts.

ReadStartElement method

public static async Task ReadStartElementAsync(this XmlReader reader, string localname, string ns)
{
    if (await reader.MoveToContentAsync() != XmlNodeType.Element)
    {
        throw new InvalidOperationException(reader.NodeType.ToString() + " is an invalid XmlNodeType");
    }
    if ((reader.LocalName == localname) && (reader.NamespaceURI == ns))
    {
        await reader.ReadAsync();
    }
    else
    {
        throw new InvalidOperationException("localName or namespace doesn’t match");
    }
}

ReadEndElement method

public static async Task ReadEndElementAsync(this XmlReader reader)
{
    if (await reader.MoveToContentAsync() != XmlNodeType.EndElement)
    {
        throw new InvalidOperationException();
    }
    await reader.ReadAsync();
}

ReadToNextSibling method

public static async Task<bool> ReadToNextSiblingAsync(this XmlReader reader, string localName, string namespaceURI)
{
    if (localName == null || localName.Length == 0)
    {
        throw new ArgumentException("localName is empty or null");
    }
    if (namespaceURI == null)
    {
        throw new ArgumentNullException("namespaceURI");
    }

    // atomize local name and namespace
    localName = reader.NameTable.Add(localName);
    namespaceURI = reader.NameTable.Add(namespaceURI);

    // find the next sibling
    XmlNodeType nt;
    do
    {
        await reader.SkipAsync();
        if (reader.ReadState != ReadState.Interactive)
            break;
        nt = reader.NodeType;
        if (nt == XmlNodeType.Element &&
             ((object)localName == (object)reader.LocalName) &&
             ((object)namespaceURI ==(object)reader.NamespaceURI))
        {
            return true;
        }
    } while (nt != XmlNodeType.EndElement && !reader.EOF);

    return false;
}

ReadToFollowing method

public static async Task<bool> ReadToFollowingAsync(this XmlReader reader, string localName, string namespaceURI)
{
    if (localName == null || localName.Length == 0)
    {
        throw new ArgumentException("localName is empty or null");
    }
    if (namespaceURI == null)
    {
        throw new ArgumentNullException("namespaceURI");
    }

    // atomize local name and namespace
    localName = reader.NameTable.Add(localName);
    namespaceURI = reader.NameTable.Add(namespaceURI);

    // find element with that name 
    while (await reader.ReadAsync())
    {
        if (reader.NodeType == XmlNodeType.Element && ((object)localName == (object)reader.LocalName) && ((object)namespaceURI == (object)reader.NamespaceURI))
        {
            return true;
        }
    }
    return false;
}

ReadToDescendant method

public static async Task<bool> ReadToDescendantAsync(this XmlReader reader, string localName, string namespaceURI)
{
    if (localName == null || localName.Length == 0)
    {
        throw new ArgumentException("localName is empty or null");
    }
    if (namespaceURI == null)
    {
        throw new ArgumentNullException("namespaceURI");
    }
    // save the element or root depth 
    int parentDepth = reader.Depth;
    if (reader.NodeType != XmlNodeType.Element)
    {
        // adjust the depth if we are on root node 
        if (reader.ReadState == ReadState.Initial)
        {
            parentDepth--;
        }
        else
        {
            return false;
        }
    }
    else if (reader.IsEmptyElement)
    {
        return false;
    }

    // atomize local name and namespace
    localName = reader.NameTable.Add(localName);
    namespaceURI = reader.NameTable.Add(namespaceURI);

    // find the descendant 
    while (await reader.ReadAsync() && reader.Depth > parentDepth)
    {
        if (reader.NodeType == XmlNodeType.Element && ((object)localName == (object)reader.LocalName) && ((object)namespaceURI == (object)reader.NamespaceURI))
        {
            return true;
        }
    }
    return false;
}

Security considerations

Consider the following when working with the XmlReader class:

  • Exceptions thrown from the XmlReader can disclose path information that you might not want bubbled up to your app. Your app must catch exceptions and process them appropriately.

  • Do not enable DTD processing if you're concerned about denial of service issues or if you're dealing with untrusted sources. DTD processing is disabled by default for XmlReader objects created by the Create method.

    If you have DTD processing enabled, you can use the XmlSecureResolver to restrict the resources that the XmlReader can access. You can also design your app so that the XML processing is memory and time constrained. For example, you can configure time-out limits in your ASP.NET app.

  • XML data can include references to external resources such as a schema file. By default, external resources are resolved by using an XmlUrlResolver object with no user credentials. You can secure this further by doing one of the following:

  • The ProcessInlineSchema and ProcessSchemaLocation validation flags of an XmlReaderSettings object aren't set by default. This helps to protect the XmlReader against schema-based attacks when it is processing XML data from an untrusted source. When these flags are set, the XmlResolver of the XmlReaderSettings object is used to resolve schema locations encountered in the instance document in the XmlReader. If the XmlResolver property is set to null, schema locations aren't resolved even if the ProcessInlineSchema and ProcessSchemaLocation validation flags are set.

    Schemas added during validation add new types and can change the validation outcome of the document being validated. As a result, external schemas should only be resolved from trusted sources.

    We recommend disabling the ProcessIdentityConstraints flag when validating untrusted, large XML documents in high availability scenarios against a schema that has identity constraints over a large part of the document. This flag is enabled by default.

  • XML data can contain a large number of attributes, namespace declarations, nested elements and so on that require a substantial amount of time to process. To limit the size of the input that is sent to the XmlReader, you can:

    • Limit the size of the document by setting the MaxCharactersInDocument property.

    • Limit the number of characters that result from expanding entities by setting the MaxCharactersFromEntities property.

    • Create a custom IStream implementation for the XmlReader.

  • The ReadValueChunk method can be used to handle large streams of data. This method reads a small number of characters at a time instead of allocating a single string for the whole value.

  • When reading an XML document with a large number of unique local names, namespaces, or prefixes, a problem can occur. If you are using a class that derives from XmlReader, and you call the LocalName, Prefix, or NamespaceURI property for each item, the returned string is added to a NameTable. The collection held by the NameTable never decreases in size, creating a virtual memory leak of the string handles. One mitigation for this is to derive from the NameTable class and enforce a maximum size quota. (There is no way to prevent the use of a NameTable, or to switch the NameTable when it is full). Another mitigation is to avoid using the properties mentioned and instead use the MoveToAttribute method with the IsStartElement method where possible; those methods don't return strings and thus avoid the problem of overfilling the NameTable collection.

  • XmlReaderSettings objects can contain sensitive information such as user credentials. An untrusted component could use the XmlReaderSettings object and its user credentials to create XmlReader objects to read data. Be careful when caching XmlReaderSettings objects, or when passing the XmlReaderSettings object from one component to another.

  • Do not accept supporting components, such as NameTable, XmlNamespaceManager, and XmlResolver objects, from an untrusted source.

The following example code shows how to use the asynchronous API to parse XML.

async Task TestReader(System.IO.Stream stream)
{
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.Async = true;

    using (XmlReader reader = XmlReader.Create(stream, settings))
    {
        while (await reader.ReadAsync())
        {
            switch (reader.NodeType)
            {
                case XmlNodeType.Element:
                    Console.WriteLine("Start Element {0}", reader.Name);
                    break;
                case XmlNodeType.Text:
                    Console.WriteLine("Text Node: {0}",
                             await reader.GetValueAsync());
                    break;
                case XmlNodeType.EndElement:
                    Console.WriteLine("End Element {0}", reader.Name);
                    break;
                default:
                    Console.WriteLine("Other node {0} with value {1}",
                                    reader.NodeType, reader.Value);
                    break;
            }
        }
    }
}

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

XNA Framework

Supported in: 3.0, 2.0, 1.0

Portable Class Library

Supported in: Portable Class Library

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show:
© 2015 Microsoft