VB .NET • Read the XML File

Listing 2. The SpeechDataReader helper class reads the XML file and returns a fully populated SpeechItem object. Each SpeechItem object extends List(Of SpeechItem), so the returned SpeechItem object is the root node of the hierarchy, with all the control phrases and all children contained within it. Note that this code relies heavily on recursion to read the XML file into the SpeechItem object.

Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Xml

Public Class SpeechDataReader
	Public Shared Function ReadData(ByVal fileName _
		As String) As SpeechItem
	If File.Exists(fileName) Then
		Dim reader As New XmlTextReader(fileName)
		Dim root As New SpeechItem

		While reader.Read()
			If Not reader.IsEmptyElement Then
			If reader.Name = "node" Then
				FillSpeechItem(root, _
					reader.ReadSubtree)
			End If
			End If
		End While

			Return root
		Else
			Return Nothing
		End If
	End Function

	Private Shared Sub FillSpeechItem(ByVal _
		parent As SpeechItem, ByVal reader As XmlReader)
		Dim si As New SpeechItem

		' Skip the first node
		reader.Read()

		While reader.Read
			If reader.NodeType = XmlNodeType.Element Then
				Select Case reader.Name
					Case "node"
						si = New SpeechItem
					Case "text"
						reader.Read()
						si.Text = reader.Value
					Case "value"
						reader.Read()
						si.Value = reader.Value
					Case "subnodes"
						FillSpeechItem(si, reader.ReadSubtree)
				End Select
			End If
			If reader.NodeType = XmlNodeType.EndElement _
				AndAlso reader.Name = "node" Then
				parent.Add(si)
			End If
		End While
	End Sub
End Class