XmlTextReader Class
Namespace: System.Xml
Assembly: System.Xml.dll
Assembly: System.Xml.dll
Implements a non-cached, forward-only reader as an XmlReader and provides direct access to the source document.
This class provides a fast, forward-only, read-only way to read an XML stream or URI. It is designed for scenarios where memory usage is a concern and the entire XML document does not need to be loaded into memory. It is the recommended way to read XML unless you need the features provided by XmlDocument.
Public Constructors
-
public XmlTextReader(string url)Initializes a new instance of the
XmlTextReader
class using the specified URI. -
public XmlTextReader(System.IO.Stream input, System.Xml.XmlNameTable nt)Initializes a new instance of the
XmlTextReader
class with the specified input stream and XmlNameTable. -
public XmlTextReader(System.IO.TextReader reader)Initializes a new instance of the
XmlTextReader
class using the specified TextReader.
Public Methods
-
public override bool Read()Reads the next node in the XML stream.
-
public override void Close()Closes the stream and reader.
-
public override string GetAttribute(int i)Gets the value of the attribute with the specified index.
-
public override string GetAttribute(string name)Gets the value of the attribute with the specified name.
Public Properties
-
public override int AttributeCount { get; }Gets the number of attributes on the current node.
-
public override string BaseURI { get; }Gets the base URI of the current node.
-
public override System.Xml.XmlNodeType NodeType { get; }Gets the node type of the current node.
-
public override string Value { get; }Gets the text value of the current node.
Example
using System;
using System.Xml;
public class Example
{
public static void Main(string[] args)
{
string xmlString = @"
Gambardella, Matthew
XML Developer's Guide
Computer
44.95
2000-10-01
An in-depth look at creating applications with XML.
Ralls, Kim
Midnight Rain
Fantasy
5.95
2000-12-16
A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.
";
using (XmlTextReader reader = new XmlTextReader(new System.IO.StringReader(xmlString)))
{
reader.WhitespaceHandling = WhitespaceHandling.None; // Ignore whitespace
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
Console.Write($"<{reader.Name}");
while (reader.MoveToNextAttribute())
{
Console.Write($" {reader.Name}=\"{reader.Value}\"");
}
Console.WriteLine(">");
break;
case XmlNodeType.Text:
Console.WriteLine($" {reader.Value}");
break;
case XmlNodeType.EndElement:
Console.WriteLine($"{reader.Name}>");
break;
}
}
}
}
}