Reading and Transforming XML Documents using Visual Basic 2005 - Reading the tags in an XML document using XMLReader
(Page 2 of 6 )
The following is the simplest code that can read and display all tags in an XML document:
PrivateSub btnShow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShow.Click
Me.TextBox1.Text = ""
Dim rd As XmlReader = XmlReader.Create(Application.ExecutablePath & "......Employee.xml")
While rd.Read
If rd.NodeType = XmlNodeType.Element Then
Me.TextBox1.Text &= rd.Name & ControlChars.NewLine
End If
End While
rd.Close()
End Sub
In the above code, I used a class called “XMLReader” available in the “System.XML” namespace. You should always use the “create” method existing in “XMLReader” class whenever you want to create an object related to the “XMLReader.” When the above code gets executed, you will receive the following output:
Employees
Employee
Empno
Ename
Sal
Deptno
.
.
.
Let us modify the above code in such a way that it gives the tags along with indentation. You can perfectly indent the tags if and only if you know the depth of each node. The following code retrieves the depth of each node and indents appropriately.
Private Sub btnShowIndentation_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShowIndentation.Click
Me.TextBox1.Text = ""
Dim rd As XmlReader = XmlReader.Create(Application.ExecutablePath & "......Employee.xml")
While rd.Read
If rd.NodeType = XmlNodeType.Element Then
Me.TextBox1.Text &= Space(rd.Depth * 4) & rd.Name & ControlChars.NewLine
End If
End While
rd.Close()
End Sub
When the above code gets executed, you will receive the following kind of output:
Employees
Employee
Empno
Ename
Sal
Deptno
Employee
Empno
Ename
Sal
Deptno
.
.
.
Next: Reading the values (or text) of XML tags in an XML document using XMLReader >>
More Visual Basic.NET Articles
More By Jagadish Chaterjee