Reading and Transforming XML Documents using Visual Basic 2005 - Reading an XML string using XMLReader
(Page 4 of 6 )
In all of the previous sections, we read XML documents using XMLReader. In this section, I shall read a string which contains XML and display the node values (or text) on to the screen.
The following routine prepares the XML string using the “StringBuilder” available in the “System.Text” namespace:
PrivateFunction getPreparedXML() As String
Dim xmlBuilder As New System.Text.StringBuilder
With xmlBuilder
.AppendLine("<?xml version=""1.0"" encoding=""utf-8""?>")
.AppendLine("<Employees>")
.AppendLine(" <Employee>")
.AppendLine(" <Empno>1001</Empno>")
.AppendLine(" <Ename>Jagadish</Ename>")
.AppendLine(" <Sal>3400</Sal>")
.AppendLine(" <Deptno>20</Deptno>")
.AppendLine(" </Employee>")
.AppendLine("</Employees>")
End With
Return xmlBuilder.ToString
End Function
The following code works with the above routine and displays the node information back to the user:
Private Sub btnXMLString_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXMLString.Click
Me.TextBox1.Text = ""
Dim strRdr As New System.IO.StringReader(getPreparedXML)
Dim rd As XmlReader = XmlReader.Create(strRdr)
While rd.Read
If rd.NodeType = XmlNodeType.Text Then
Me.TextBox1.Text &= rd.ReadString & ControlChars.NewLine
End If
End While
rd.Close()
strRdr.Close()
End Sub
If you wanted to go (parse) through the XML document tag by tag (including every start and end element of every tag), you can modify the above code as follows:
Private Sub btnReadNodes_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReadNodes.Click
Me.TextBox1.Text = ""
Dim strRdr As New System.IO.StringReader(getPreparedXML)
Dim rd As XmlReader = XmlReader.Create(strRdr)
rd.Read()
rd.ReadStartElement("Employees")
rd.ReadStartElement("Employee")
rd.ReadStartElement("Empno")
Me.TextBox1.Text &= rd.ReadString & ControlChars.NewLine
rd.ReadEndElement() 'end empno
rd.ReadStartElement("Ename")
Me.TextBox1.Text &= rd.ReadString & ControlChars.NewLine
rd.ReadEndElement() 'end ename
rd.ReadStartElement("Sal")
Me.TextBox1.Text &= rd.ReadString & ControlChars.NewLine
rd.ReadEndElement() 'end sal
rd.ReadStartElement("Deptno")
Me.TextBox1.Text &= rd.ReadString & ControlChars.NewLine
rd.ReadEndElement() 'end deptno
rd.ReadEndElement() 'end employee
rd.ReadEndElement() 'end employees
rd.Close()
strRdr.Close()
End Sub
Next: Transforming an XML document to HTML using XSLT with VB 2005 >>
More Visual Basic.NET Articles
More By Jagadish Chaterjee