Microsoft KB Archive/317597

= How to populate a TreeView control with XML data in Visual C# 2005 or in Visual C# .NET =

Article ID: 317597

Article Last Modified on 5/17/2007

-

APPLIES TO


 * Microsoft Visual C# 2005 Express Edition
 * Microsoft Visual C# .NET 2003 Standard Edition
 * Microsoft Visual C# .NET 2002 Standard Edition
 * Microsoft .NET Framework 1.1
 * Microsoft .NET Framework 1.0

-



This article was previously published under Q317597





For a Microsoft Visual Basic .NET version of this article, see 308063.



SUMMARY
This step-by step article describes how to populate a TreeView control by using Extensible Markup Language (XML) data in Microsoft Visual C# 2005 or in Microsoft Visual C# .NET. Because both XML and the TreeView control represent the data in a hierarchical format, the TreeView control is a natural choice to display XML data.

The TreeView control has a Nodes collection with root TreeNode objects. Each TreeNode in turn has its own Nodes collection that holds more than one child TreeNode.

Note This sample uses the Document Object Model (DOM) parsing classes of .NET to process XML.

For more information about the design of XML in .NET Framework, see the &quot;References&quot; section.

Requirements
The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
 * Microsoft Windows XP, Microsoft Windows 2000, or Microsoft Windows NT 4.0 Service Pack 6a
 * Microsoft Data Access Components 2.6 (MDAC) or later
 * Microsoft Visual Studio 2005 or Microsoft Visual Studio .NET

This article assumes that you are familiar with the following topics:
 * Visual C# 2005 syntax or Visual C# .NET syntax
 * XML and the related standards
 * Windows Forms

Steps to create and populate the TreeView Control with XML
  Paste the following XML sample code in a new text file named &quot;Sample.xml&quot;. This file is the sample XML data for this example:  id=&quot;grandfather&quot; id=&quot;father&quot; id=&quot;brother&quot; id=&quot;niece&quot; id=&quot;me&quot; id=&quot;son&quot; id=&quot;daughter&quot; id=&quot;sister&quot; id=&quot;uncle&quot; id=&quot;cousin sister&quot; id=&quot;second cousin&quot; id=&quot;cousin brother&quot;  Create a new Windows-based application in Visual C# 2005 or in Visual C# .NET. Form1 is added to the application by default. Drag new TreeView, Button, Label, and TextBox controls onto Form1.  Add the following sample code at the end of the using directives section in Form1.cs: using System.Xml;   Paste the following sample code into the Form1_Load event: // Initialize the controls and the form. label1.Text = &quot;File Path&quot;; label1.SetBounds(8, 8, 50, 20); textBox1.Text = Application.StartupPath + &quot;\\Sample.xml&quot;; textBox1.SetBounds(64, 8, 256, 20); button1.Text = &quot;Populate the TreeView with XML&quot;; button1.SetBounds(8, 40, 200, 20); this.Text = &quot;TreeView control from XML&quot;; this.Width = 336; this.Height = 368; treeView1.SetBounds(8, 72, 312, 264);   Paste the following code into the Button1_Click event: try {           // SECTION 1. Create a DOM Document and load the XML data into it. XmlDocument dom = new XmlDocument; dom.Load(textBox1.Text);

// SECTION 2. Initialize the TreeView control. treeView1.Nodes.Clear; treeView1.Nodes.Add(new TreeNode(dom.DocumentElement.Name)); TreeNode tNode = new TreeNode; tNode = treeView1.Nodes[0];

// SECTION 3. Populate the TreeView with the DOM nodes. AddNode(dom.DocumentElement, tNode); treeView1.ExpandAll; }        catch(XmlException xmlEx) {           MessageBox.Show(xmlEx.Message); }        catch(Exception ex) {           MessageBox.Show(ex.Message); }                   </li>  Paste the following sample code after the Button1_Click event: private void AddNode(XmlNode inXmlNode, TreeNode inTreeNode) {        XmlNode xNode; TreeNode tNode; XmlNodeList nodeList; int i;

// Loop through the XML nodes until the leaf is reached. // Add the nodes to the TreeView during the looping process. 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 {           // Here you need to pull the data from the XmlNode based on the // type of node, whether attribute values are required, and so forth. inTreeNode.Text = (inXmlNode.OuterXml).Trim; }     }                     } }                    </li> Press F5 to build and run the application. Make sure that the XML file path is correct and then click the button. The XML data should appear in the TreeView control.</li></ol>

Note The resource could be a file, a URL or an XML Stream. See the &quot;References&quot; section for information about using the XmlDocument class to load XML data from different resources.

Steps to populate the TreeView Control with required data
The previous code sample maps the XML tree data directly onto the TreeView and displays all the data. Alternatively, you can add extra information to the display or skip unwanted data.

In many instances, you may want to display only part of the XML data. The portion of the data that you want to display may be dynamically constructed, the result of an Extensible Stylesheet Language (XSL) transformation, or the result of an XPath query. This section describes how to build a new XML document with only the required nodes and then add the new document to the TreeView control.

For example, the following steps retrieve only the child elements of the originial XML data by using XPath query, and then add this list as a new node to the TreeView. <ol>  Paste following code just before the TreeView1.ExpandAll line in the previous sample: // SECTION 4. Create a new TreeView Node with only the child nodes. XmlNodeList nodelist = dom.SelectNodes(&quot;//child&quot;); XmlDocument cDom = new XmlDocument; cDom.LoadXml(&quot; &quot;); foreach(XmlNode node in nodelist) {              XmlNode newElem = cDom.CreateNode(XmlNodeType.Element, node.Name, node.LocalName); newElem.InnerText = node.InnerText; cDom.DocumentElement.AppendChild(newElem); }           treeView1.Nodes.Add(new TreeNode(cDom.DocumentElement.Name)); tNode = treeView1.Nodes[1]; AddNode(cDom.DocumentElement, tNode); </li> Build and then run the application. This application should display a new &quot;children&quot; root node in the TreeView in addition to the original data.</li></ol>