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:

 

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

ReadXMLFile()

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> “)

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

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

Writer.Write(R.Name)

Writer.Write(“<br>”)

End If

‘ The value is when reading the inner content.

If (R.Value <> “”) Then

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

Writer.Write(R.Value)

Writer.Write(“<br>”)

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(R.GetAttribute(I))

Writer.Write(” “)

Next I

Writer.Write(“<br>”)

End If

Writer.Write(“<br>”)

End While

Fs.Close()

‘ 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