When to Use XmlReader

Since XmlReader is a read-only XML parser, you should use it when you need to read an XML file or stream and convert it into a data structure in memory, or when you need to output it into another file or stream. Because it is a forward-only XML parser, XmlReader may be used only to read data from beginning to end. These qualities combine to make XmlReader very efficient in its use of memory; only the minimum amount of data required is held in memory at any given time. Although you can use XmlReader to read XML to be consumed by one of .NET’s implementations of DOM, XML Schema, or XSLT (each of which is discussed in later chapters), it’s usually not necessary, as each of these types provides its own mechanism for reading XML—usually using XmlReader internally themselves!

On the other hand, XmlReader can be a useful building block in an application that needs to manipulate XML data in ways not supported directly by a .NET type. For example, to create a SAX implementation for .NET, you could use XmlReader to read the XML input stream, just as other .NET XML types, such as XmlDocument, do.

You can also extend XmlReader to provide a read-only XML-style interface to data that is not formatted as XML; indeed, I’ll show you how to do just that in Chapter 4. The beauty of using XmlReader for non-XML data is that once you’ve written the code to respond to XmlReader events, handling a different format is a simple matter of dropping in a specialized, format-specific ...

Get .NET & XML now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.