How to create a TreeView from XML File

XML, being a self-describing language, not only encapsulates data within its tags but also provides the accompanying rules and specifications required for accurate extraction and interpretation of the contained information.


When we engage in reading an XML file, we are effectively accessing and extracting the data that resides within the designated XML tags present in the file. This process enables us to comprehend and utilize the information embedded within the tags, ensuring precise data retrieval and interpretation.

TreeView from XML File

In the previous example, we explored the process of reading an XML file in a node-wise manner. In this scenario, we continue the XML file reading process by treating each node as a separate entity and transferring the node's data to a TreeView control. By adopting this approach, we can effectively represent the hierarchical structure of the XML file within the TreeView, facilitating intuitive navigation and visualization of the XML data. This enables users to traverse the XML file's content in a structured manner, further enhancing the understanding and accessibility of the information contained within the XML file.

Full Source C#
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