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:
Public Class ReadXMLFile
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
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.
‘ 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
‘ The value is when reading the inner content.
If (R.Value <> “”) Then
If (R.AttributeCount > 0) Then
For I As Integer = 0 To R.AttributeCount – 1
‘ Copy the string content into a label to display it.
lblXml.Text = Writer.ToString()
The code produces the result shown in the next picture: