Bind Treeview from xml file at runtime in C#

The basic similarity in the XML file and treeview control is the representation of the data in a hierarchical format. So we can bind the treeview control from the XML file. In this article i will explain you how we can do it.

 

 
Suppose we have an XML file capitals.xml with the following data:

<?xml version='1.0'?>
<Capitals>
  <Country>
   <Name>
     India
   </Name>
   <Capital>
     NewDelhi
   </Capital>
  </Country>
  <Country>
   <Name>
     USA
   </Name>
   <Capital>
     Washington
   </Capital>
  </Country>
</Capitals>

The following is the C# code for populating treeview control named treeview1. Use the System.xml directive on the top of the your .cs file:

using System.Xml;

In the following code first we load the XML file in the object of the xmlDocument class and then bind nodes to treeview through loop for the document nodes.

       private void BindTreeView()
       {
           try
           {
               XmlDocument xmlDoc = new XmlDocument();
               xmlDoc.Load("C:\\Capitals.xml");
               treeView1.Nodes.Clear();
               treeView1.Nodes.Add(new TreeNode(xmlDoc.DocumentElement.Name));
               TreeNode rootNode = treeView1.Nodes[0];
               AddTreeNode(xmlDoc.DocumentElement, rootNode);
               treeView1.ExpandAll();
           }
           catch (XmlException xmlEx)
           {
               MessageBox.Show(xmlEx.Message);
           }
           catch (System.Exception ex)
           {
               MessageBox.Show(ex.Message);
           }
       }
       private void AddTreeNode(XmlNode xmlNode, TreeNode treeNode)
       {
           XmlNode newNode;
           TreeNode tNode;
           XmlNodeList nodeList;
           int i;
           if (xmlNode.HasChildNodes)
           {
               nodeList = xmlNode.ChildNodes;
               for (i = 0; i <= nodeList.Count - 1; i++)
               {
                   newNode = xmlNode.ChildNodes[i];
                   treeNode.Nodes.Add(new TreeNode(newNode.Name));
                   tNode = treeNode.Nodes[i];
                   AddTreeNode(newNode, tNode);
               }
           }
           else
           {
               treeNode.Text = (xmlNode.OuterXml).Trim();
           }
       }

try the above code.