How to create a TreevView from XML

In the previous example, we learned how to read an XML file node by node. Now, we will take it a step further and demonstrate how to read the XML file and populate a TreeView control with the data.

To achieve this, we will use the XmlReader class to read the XML file. The XmlReader provides a forward-only, read-only access to XML data, making it efficient for parsing large XML files. We will traverse through the XML file and extract the necessary data from each node.

Once we have obtained the data from the XML file, we can populate a TreeView control. The TreeView control is a hierarchical control that allows us to display data in a tree-like structure. Each node in the TreeView represents a data element from the XML file.


Populate the TreeView

To populate the TreeView, we will loop through the XML nodes and create corresponding TreeView nodes for each node. We will assign the appropriate attributes, such as the node's text, value, and parent-child relationships. By adding these nodes to the TreeView control, we can visually represent the XML data in a structured manner.

Additionally, we can enhance the user experience by customizing the appearance of the TreeView nodes, such as setting icons, colors, and styles. This allows for better visualization and interaction with the XML data.

Full Source VB.NET
Imports System.Xml Imports 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) xmldoc.Load(fs) xmlnode = xmldoc.ChildNodes(1) TreeView1.Nodes.Clear() 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) Next Else inTreeNode.Text = inXmlNode.InnerText.ToString End If End Sub End Class

Click here to download the input file tree.xml


The provided program demonstrates how to read an XML file node by node and populate a TreeView control with the data. By utilizing the XmlReader class to traverse through the XML file and creating corresponding TreeView nodes, we can visualize the XML data in a hierarchical format.