How to create a TreeView from XML File in C#

Total Post:412

Points:2888
C# 
C#
 2192  View(s)
Ratings:
Rate this:
Hi Developers,

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

Thanks in advance.
  1. 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();
                }
            }
        }
    }

      Modified On Mar-30-2018 04:06:00 AM

Answer

NEWSLETTER

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