Tuesday, April 15, 2014

Read data from XML file and Load to Tree control C# Code

This post is showing, how to read the data form XML file and load to Tree Control in ASP.NET using C#.
I created a XML file as below:

Create ASP.NET empty web application and under the form just drag and drop the Tree Control which is under navigation tag.

The sample code shows below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

namespace XMLDemo
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            //Create a doc Document and load the XML data into it.
            XmlDocument doc = new XmlDocument();
            doc.Load("E://Testing.NET//StudentList.xml");
            XmlNodeList studentList = doc.SelectNodes("/");

            // SECTION 2. Initialize the TreeView control.
            TreeView1.Nodes.Clear();
            TreeView1.Nodes.Add(new TreeNode(doc.DocumentElement.Name));
            TreeNode tNode = new TreeNode();
            tNode = TreeView1.Nodes[0];

            // SECTION 3. Populate the TreeView with the DOM nodes.
            AddNode(doc.DocumentElement, tNode);
            TreeView1.ExpandAll();

        }

        private void AddNode(XmlNode inXmlNode, TreeNode inTreeNode)
        {
            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.ChildNodes.Add(new TreeNode(xNode.Name));
                    tNode = inTreeNode.ChildNodes[i];
                    AddNode(xNode, tNode);
                }
            }
            else
            {
                // Here you need to pull the data from the XmlNode based on the
                // type of node, whether attribute values are required, and so forth.
                inTreeNode.Text = (inXmlNode.OuterXml).Trim();
            }
        }
    }
}

The output will be like as below.

No comments:

Post a Comment