Home > DeveloperSection > Blogs > Bind XML file in Tree View control using C#

Bind XML file in Tree View control using C#


C# C# 
Ratings:
0 Comment(s)
 7178  View(s)
Rate this:

Bind XML file in Tree View control using C#

In this blog I am trying to explain how to bind the XML file in tree view control.

XML

XML is a self describing language and it provides data as well as the rules to extract what the data it contains.

Steps for creating this demo.

1.       Open Visual Studio 2010.

2.       Create new project with appropriate name.

3.       Drag and drop a tree view in form.

4.       Write below code in you editor.

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Xml;

using System.IO;

namespace MinimizDemo

{

    public partial class Form3 : Form

    {

        public Form3()

        {

            InitializeComponent();

        }

        private void Form3_Load(object sender, EventArgs e)

        {

            XmlDataDocument xmldoc = new XmlDataDocument();

            XmlNode xmlnode;

            FileStream fs = new FileStream(@"D:\Vijay\2013\June\14-06-2013 (Friday)\Demo\Windows\MinimizDemo\MinimizDemo\tree.xml", FileMode.Open, FileAccess.Read);

            xmldoc.Load(fs);

            xmlnode = xmldoc.ChildNodes[1];

            treeView1.Nodes.Clear();

            treeView1.Nodes.Add(new TreeNode(xmldoc.DocumentElement.Name));

            TreeNode tNode;

            tNode = treeView1.Nodes[0];

            AddNode(xmlnode, tNode);

        }

        private void AddNode(XmlNode inXmlNode, TreeNode inTreeNode)

        {

            XmlNode xNode;

            TreeNode tNode;

            XmlNodeList nodeList;

            int i = 0;

            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(xNode, tNode);

                }

            }

            else

            {

                inTreeNode.Text = inXmlNode.InnerText.ToString();

            }

        }

    }

}

Output: -

Note: - I got book.xml file from this link


Don't want to miss updates? Please click the below button!

Follow MindStick