Populate Treeview control from an XML file in C#.net

How to Populate Treeview control from an XML file in C#.net

Populate Treeview control from an XML file in C#.net

The following Program loads an XML file into a tree view control.

using System.Xml; 
 
private void btnLoadXMLFile_Click(object sender, System.EventArgs e)
{
    try
    {
 
        string strXPath = "XML/I140";
        string strRootNode = "Treeview Demo";
        string strXMLFile = @"C:\CSharpCode\Treeview.xml";
 
        // Load the XML file.
        XmlDocument dom   = new XmlDocument();
        dom.Load(strXMLFile);
 
        // Load the XML into the TreeView.
        this.treeView1.Nodes.Clear();
        this.treeView1.Nodes.Add(new TreeNode(strRootNode));
        TreeNode tNode = new TreeNode();
        tNode          = this.treeView1.Nodes[0];
 
        XmlNodeList oNodes = dom.SelectNodes(strXPath);
        XmlNode xNode      = oNodes.Item(0).ParentNode;
 
        AddNode(ref xNode, ref tNode);
 
        this.treeView1.CollapseAll();
        this.treeView1.Nodes[0].Expand();
        this.Cursor = System.Windows.Forms.Cursors.Default;
    }
 
    catch (Exception ex)
    {
             MessageBox.Show(ex.Message, "Error");
    }    
}
 
private void AddNode(ref XmlNode inXmlNode, ref TreeNode inTreeNode)
{
    // Recursive routine to walk the XML DOM and add its nodes to a TreeView.
    XmlNode     xNode;
    TreeNode    tNode;
    XmlNodeList nodeList;
    int i;
 
    // Loop through the XML nodes until the leaf is reached.
    // Add the nodes to the TreeView during the looping process.
    if (inXmlNode.HasChildNodes)
    {
        nodeList = inXmlNode.ChildNodes;
        for (i = 0; i <= nodeList.Count - 1; i++)
        {
            xNode = inXmlNode.ChildNodes[i];
            inTreeNode.Nodes.Add(new TreeNode(xNode.Name));
            tNode = inTreeNode.Nodes[i];
            AddNode(ref xNode, ref tNode);
        }
    }
    else
    {
        inTreeNode.Text = inXmlNode.OuterXml.Trim();
    }
}
 
private void btnExpand_Click(object sender, System.EventArgs e)
{
    if (this.btnExpand.Text == "Expand All Nodes")
    {
        this.treeView1.ExpandAll();
        this.btnExpand.Text = "Collapse All Nodes";
    }       
    else
    {
        this.treeView1.CollapseAll();
        this.treeView1.Nodes[0].Expand();
        this.btnExpand.Text = "Expand All Nodes";
    }
} 

 

By Kalit Sikka   Popularity  (5227 Views)