Home > DeveloperSection > Forums > How to create a TreeView from XML File in C#
Pravesh Singh

Total Post:411

Posted on    June-15-2013 5:23 AM

 C# C# 

 1 Reply(s)
 1497  View(s)
Rate this:
Hi Developers,

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

Thanks in advance.

Sumit Kesarwani

Total Post:378

Posted on    June-15-2013 7:11 AM

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()





        private void button1_Click(object sender, EventArgs e)


            XmlDataDocument xmldoc = new XmlDataDocument();

            XmlNode xmlnode;

            FileStream fs = new FileStream("tree.xml", FileMode.Open, FileAccess.Read);


            xmlnode = xmldoc.ChildNodes[1];


            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);





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





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

Follow MindStick