Reading and Transforming XML Documents using Visual Basic 2005 - Reading the values (or text) of XML tags in an XML document using XMLReader
(Page 3 of 6 )
In the previous section, we read only the tags available in an XML document. In this section, we will read the values and also the related tags along with them. First of all, let us concentrate on reading values. Consider the following code:
PrivateSub btnShowValues_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShowValues.Click
Me.TextBox1.Text = ""
Dim rd As XmlReader = XmlReader.Create(Application.ExecutablePath & "......Employee.xml")
While rd.Read
If rd.NodeType = XmlNodeType.Text Then
Me.TextBox1.Text &= rd.ReadString & ControlChars.NewLine
End If
End While
rd.Close()
End Sub
You can observe that I am comparing with the “text” type of SML node to retrieve the values available in XML document. You can also observe that I am using the “ReadString” method to read the value.
Finally, the following code retrieves each and every tag along with its name, text, and so forth:
PrivateSub btnShowXML_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShowXML.Click
Me.TextBox1.Text = ""
Dim rd As XmlReader = XmlReader.Create(Application.ExecutablePath & "......Employee.xml")
While rd.Read
Select Case rd.NodeType
Case XmlNodeType.Element
Me.TextBox1.Text &= Space(rd.Depth * 4) & String.Format("<{0}>", rd.Name) & ControlChars.NewLine
Case XmlNodeType.Text
Me.TextBox1.Text &= Space(rd.Depth * 4) & String.Format(rd.Value) & ControlChars.NewLine
Case XmlNodeType.CDATA
Me.TextBox1.Text &= Space(rd.Depth * 4) & String.Format("<![CDATA[{0}]]>", rd.Value) & ControlChars.NewLine
Case XmlNodeType.ProcessingInstruction
Me.TextBox1.Text &= Space(rd.Depth * 4) & String.Format("<?{0} {1}?>", rd.Name, rd.Value) & ControlChars.NewLine
Case XmlNodeType.Comment
Me.TextBox1.Text &= Space(rd.Depth * 4) & String.Format("<!--{0}-->", rd.Value) & ControlChars.NewLine
Case XmlNodeType.XmlDeclaration
Me.TextBox1.Text &= Space(rd.Depth * 4) & String.Format("<?xml version='1.0'?>") & ControlChars.NewLine
Case XmlNodeType.Document
Case XmlNodeType.DocumentType
Me.TextBox1.Text &= Space(rd.Depth * 4) & String.Format("<!DOCTYPE {0} [{1}]", rd.Name, rd.Value) & ControlChars.NewLine
Case XmlNodeType.EntityReference
Me.TextBox1.Text &= Space(rd.Depth * 4) & String.Format(rd.Name) & ControlChars.NewLine
Case XmlNodeType.EndElement
Me.TextBox1.Text &= Space(rd.Depth * 4) & String.Format("</{0}>", rd.Name) & ControlChars.NewLine
End Select
End While
rd.Close()
End Sub
Next: Reading an XML string using XMLReader >>
More Visual Basic.NET Articles
More By Jagadish Chaterjee