How to create a TreevView from XML

XML is a self describing language and it gives the data as well as the rules to extract what the data it contains. Reading an XML file means that we are reading the data embedded in tags in an XML file.


In the previous example we already saw how to read an XML file Node wise. Here we are reading XML file as Node and pass the Nodes data to TreeView.

Imports System.Xml
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim xmldoc As New XmlDataDocument()
        Dim xmlnode As XmlNode
        Dim fs As New FileStream("tree.xml", FileMode.Open, FileAccess.Read)
        xmlnode = xmldoc.ChildNodes(1)
        TreeView1.Nodes.Add(New TreeNode(xmldoc.DocumentElement.Name))
        Dim tNode As TreeNode
        tNode = TreeView1.Nodes(0)
        AddNode(xmlnode, tNode)
    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
            For i = 0 To nodeList.Count - 1
                xNode = inXmlNode.ChildNodes(i)
                inTreeNode.Nodes.Add(New TreeNode(xNode.Name))
                tNode = inTreeNode.Nodes(i)
                AddNode(xNode, tNode)
            inTreeNode.Text = inXmlNode.InnerText.ToString
        End If
    End Sub
End Class

Click here to download the input file tree.xml