Net-informations.com
SiteMap  | About    

How to create a TreeView from XML File

XML is a self describing language and it gives the data as well as the rules to extract what the data it contains. Reading an XML file means that we are reading the data embedded in tags in an XML file.

xml-tree

In the previous example we already saw how to read an XML file Node wise. Here we are reading XML file as Node and pass the Nodes data to TreeView .




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

Click here to download the input file tree.xml






net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.