Populate Treeview control from an XML file using C#

The following C# code loads an XML file into a tree view control. All you need to do is set the path to the XML file and specify the XPATH to the top node.

using System.Xml; 

private void button1_Click(object sender, System.EventArgs e)
{
    try
    {
        this.Cursor = System.Windows.Forms.Cursors.WaitCursor;

        string strXPath = "XML/I140";
        string strRootNode = "Treeview Sample";
        string strXMLFile = @"C:\...\test.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)
    {
        this.Cursor = System.Windows.Forms.Cursors.Default;
        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";
    }
} 



About TheScarms
About TheScarms


Sample code
version info

If you use this code, please mention "www.TheScarms.com"

Email this page


© Copyright 2024 TheScarms
Goto top of page