Represents a reader that provides fast, forward-only access to a stream of XML data. This is the base class for all XmlReader
implementations.
The XmlReader
class provides a way to read XML documents in a forward-only, read-only manner. This makes it very efficient for processing large XML files. The XmlReaderImplementation
abstract class defines the core functionality and interface that all concrete XmlReader
classes must adhere to.
Key features include:
XmlReader
.Gets the number of attributes on the current node.
Gets the base URI of the current node.
Gets the type of the current node.
Gets the qualified name of the current node.
Gets the local name of the current node.
Gets the value of the current node.
Moves to the next attribute. Returns true
if there is a next attribute, otherwise false
.
Reads the next node from the XML stream. Returns true
if there are more nodes to read, otherwise false
.
Closes the XmlReader
object and the underlying streams.
The following example demonstrates basic usage of an XmlReader
to iterate through XML nodes. Note that XmlReaderImplementation
itself is abstract and cannot be instantiated directly. Concrete implementations like XmlTextReader
or XmlDictionaryReader
are used.
// This example uses XmlTextReader, a concrete implementation of XmlReader. using System; using System.Xml; public class XmlReaderExample { public static void Main(string[] args) { string xmlString = @"<bookstore><book category='cooking'><title lang='en'>Everyday Italian</title><author>Giada De Laurentiis</author><year>2005</year><price>30.00</price></book></bookstore>"; using (XmlReader reader = XmlReader.Create(new System.IO.StringReader(xmlString))) { while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: Console.WriteLine($"<{reader.Name}>"); if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { Console.WriteLine($" Attribute: {reader.Name} = {reader.Value}"); } } break; case XmlNodeType.Text: Console.WriteLine($" Text: {reader.Value}"); break; case XmlNodeType.XmlDeclaration: case XmlNodeType.DocumentType: Console.WriteLine($"<?{reader.Name}... ?>"); break; case XmlNodeType.EndElement: Console.WriteLine($"</{reader.Name}>"); break; } } } } }