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.

C# 8.0 and .NET Core 3.0 – Modern Cross-Platform Development: Build applications with C#, .NET Core, Entity Framework Core, ASP.NET Core, and ML.NET using Visual Studio Code, 4th Edition
ASP.NET Core 3 and Angular 9: Full stack web development with .NET Core 3.1 and Angular 9, 3rd Edition
C# in Depth, 4th Edition

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:


Imports System

Imports System.Collections.Generic

Imports System.Linq

Imports System.Web

Imports System.Web.UI

Imports System.Web.UI.WebControls

Imports System.IO

Imports System.Xml


Public Class ReadXMLFile

Inherits System.Web.UI.Page


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

If Not Me.IsPostBack Then


End If

End Sub

Protected Sub ReadXMLFile()

Dim File As String = Path.Combine(Request.PhysicalApplicationPath, “App_Data\BooksList.xml”)

Dim Fs As FileStream = New FileStream(File, FileMode.Open)

Dim R As XmlTextReader = New XmlTextReader(Fs)

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

‘ describes the information read from the XML document.

Dim Writer As StringWriter = New StringWriter()

‘ Parse the file, and read each node.

While (R.Read())

Writer.Write(“<b>Type:</b> “)



‘ 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 <> “”) Then

Writer.Write(“<b>Name:</b> “)



End If

‘ The value is when reading the inner content.

If (R.Value <> “”) Then

Writer.Write(“<b>Value:</b> “)



End If

If (R.AttributeCount > 0) Then

Writer.Write(“<b>Attributes:</b> “)

For I As Integer = 0 To R.AttributeCount – 1

Writer.Write(” “)


Writer.Write(” “)

Next I


End If


End While


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

lblXml.Text = Writer.ToString()


End Sub

End Class

The code produces the result shown in the next picture:

Using of XmlTextReader to read XML file as text

Using of XmlTextReader to read XML file as text