Load XML file data in a Treeview control in Visual Basic 2005

We have an XML file that needs to be loaded in the TreeView control. This entry shows How do we do it in VB.NET 2005.

Let's create a VB.NET Project. Drag and drop a TreeViewControl and name it tvwMetabase. Also drag a Button control and name it btnLoad. Modify the path of the following code to point to any valid xml file and run the project. On clicking your Button you should see the Treeview control loaded with the XML file's data!!

    Private Sub btnLoadXML_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs _
) Handles btnLoad.Click
Try
Dim xmlDoc As New XmlDocument()
Dim tnNode As TreeNode
xmlDoc.Load("C:\Metabase.xml") '<--- Change this path with a valid XML file
tvwMetabase.Nodes.Clear()
tvwMetabase.Nodes.Add(xmlDoc.DocumentElement.Name)
tnNode = New TreeNode
tnNode = tvwMetabase.Nodes(0)
AddNode(xmlDoc.DocumentElement, tnNode)
Catch xmlEx As XmlException
MessageBox.Show(xmlEx.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub AddNode(ByVal inXmlNode As XmlNode, ByVal inTreeNode As TreeNode)
Dim xNode As XmlNode
Dim tNode As TreeNode
Dim nodeList As XmlNodeList
Dim i As Integer
If inXmlNode.HasChildNodes Then
nodeList = inXmlNode.ChildNodes
i = 0
While i <= nodeList.Count - 1
xNode = inXmlNode.ChildNodes(i)
inTreeNode.Nodes.Add(New TreeNode(xNode.Name))
tNode = inTreeNode.Nodes(i)
AddNode(xNode, tNode)
i += 1
End While
Else
inTreeNode.Text = (inXmlNode.OuterXml).Trim
End If
End Sub

Enjoy!
-Rahul Soni