The XmlReader and XmlTextReader classes are defined in the System. XML namespace.
The XmlTextReader class is derived from the XmlReader class. The XmlTextReader class can be used to read XML documents. This type of Read method reads this document until its node ends.
In this article, we will demonstrate how to use the XmlTextReader class to read an XML document and output data to the console.
Add namespace reference
Because Xml classes are defined in the System. Xml namespace, the first thing to do is to add a reference to System. Xml in the project.
Using System. Xml;
Open an XML document
The XmlTextReader class constructor opens an XML file. In this example, a file named xmltest. xml is used and stored in the C: temp directory. You can download this attachment.
// Open an XML file
XmlTextReader reader = new XmlTextReader ("C: \ temp \ xmltest. xml ");
Read data
The Read method of the XmlTextReader class reads data.
While (reader. Read ())
{
Console. WriteLine (reader. Name );
}
Source code:
Attachment
CS Code
XML file
Namespace ReadXML
{
Using System;
Using System. Xml;
Public static int Main (string [] args)
{
Try
{
// Open an XML file
XmlTextReader reader = new XmlTextReader ("C: \ temp \ xmltest. xml ");
While (reader. Read ())
{
Console. WriteLine (reader. Name );
}
}
Catch (Exception e)
{
Console. WriteLine ("Exception: {0}", e. ToString ());
}
Return 0;
}
}
}