Reading XML Files

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. The read function of this document reads the document until the end of its nodes.

In this article, I will show you how to use the XmlTextReader class to read an XML document and write data to the console.

Adding namspace Reference

Since XML classes are defined in the System.XML namespace the first thing you need to do is to add the System.XML reference to the project.

using System.Xml;

Open an XML Document

The constructor of the XmlTextReader class opens an XML file. In this sample, I used an XML file called xmltest.xml in the C\temp directory. You can download the attached file.

// Open an XML file
XmlTextReader reader = new XmlTextReader("C:\\temp\\xmltest.xml");

Reading  Data

The Read method of the XmlTextReader class reads the data.

while ( reader.Read() )
{
Console.WriteLine(reader.Name);
}

Souce Code: Attachment readxml1.cs 1 KB,  xmltest.xml 1 KB

namespace ReadXML
{
using System;
using System.Xml;
/// <summary>
/// Summary description for Class1.
/// </summary>
public class Class1
{
public Class1()
{
}
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;
}
}
}


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.