HOW TO CREATE A TREEVIEW FROM XML FILE IN C#

Pravesh Singh

Total Post:412

Points:2888
Posted by  Pravesh Singh
C# 
C#
 1850  View(s)
Ratings:
Rate this:
Hi Developers,

How to create a TreeView from XML File in C#?

Thanks in advance.
  1. Sumit Kesarwani

    Post:378

    Points:2694
    Re: How to create a TreeView from XML File in C#

    Hi Pravesh,

    You can use this code:

    using System;

    using System.Data;

    using System.Windows.Forms;

    using System.Xml;

    using System.IO;

     

    namespace WindowsApplication1

    {

        public partial class Form1 : Form

        {

            public Form1()

            {

                InitializeComponent();

            }

     

            private void button1_Click(object sender, EventArgs e)

            {

                XmlDataDocument xmldoc = new XmlDataDocument();

                XmlNode xmlnode;

                FileStream fs = new FileStream("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();

                }

            }

        }

    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!