How to use XmlTextReader to read XML file as text in C#

You can use the XmlTextReader class when you want to read a XML document in your code. The XmlTextReader moves through your document from top to bottom, one node at a time. You call the Read() method to move to the next node. This method returns true if there are more nodes to read or false once it has read the final node. The current node is provided through the properties of the XmlTextReader class, such as NodeType and Name.

A node is a designation that includes comments, whitespace, opening tags, closing tags, content, and even the XML declaration at the top of your file. To get a quick understanding of nodes, you can use the XmlTextReader to run through your entire document from start to finish and display every node it encounters. The code for this task is as follows:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.IO;

using System.Xml;

 

namespace WriteToXMLFileVC

{

public partial class XMLReader : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

if (!this.IsPostBack)

{

ReadXMLFile();

}

}

protected void ReadXMLFile()

{

string file = Path.Combine(Request.PhysicalApplicationPath, @”App_Data\BooksList.xml”);

FileStream fs = new FileStream(file, FileMode.Open);

XmlTextReader r = new XmlTextReader(fs);

// Use a StringWriter to build up a string of HTML that

// describes the information read from the XML document.

StringWriter writer = new StringWriter();

// Parse the file, and read each node.

while (r.Read())

{

writer.Write(“<b>Type:</b> “);

writer.Write(r.NodeType.ToString());

writer.Write(“<br>”);

// The name is available when reading the opening and closing tags

// for an element. It’s not available when reading the inner content.

if (r.Name != “”)

{

writer.Write(“<b>Name:</b> “);

writer.Write(r.Name);

writer.Write(“<br>”);

}

// The value is when reading the inner content.

if (r.Value != “”)

{

writer.Write(“<b>Value:</b> “);

writer.Write(r.Value);

writer.Write(“<br>”);

}

if (r.AttributeCount > 0)

{

writer.Write(“<b>Attributes:</b> “);

for (int i = 0; i < r.AttributeCount; i++)

{

writer.Write(” “);

writer.Write(r.GetAttribute(i));

writer.Write(” “);

}

writer.Write(“<br>”);

}

writer.Write(“<br>”);

}

fs.Close();

// Copy the string content into a label to display it.

lblXml.Text = writer.ToString();

}

}

}

The code produces the result shown in the next picture:

 

Using of XmlTextReader to read XML file as text in C#

Using of XmlTextReader to read XML file as text in C#