Populating a TreeView Control from XML
This post describes how to populate a WinForms TreeView control from an XML file assuming you are targeting the .NET Framework Version 3.5.
The XML file used in this example looks like this:
<States>
<State name="California">
<Regions>
<Region name="San Luis Obispo">
<Area name="Santa Maria" />
<Area name="Seaside" />
</Region>
<Region name="Silicon Valley">
<Area name="San Jose"/>
<Area name="Sunnyvale"/>
</Region>
</Regions>
</State>
<State name="Wisconsin">
<Regions>
<Region name="Milwaukee">
<Area name ="Mukwanago"/>
<Area name="Germantown"/>
</Region>
<Region name="Fox Valley">
<Area name="Oshkosh" />
<Area name="Appleton" />
</Region>
</Regions>
</State>
</States>
The TreeView will display the following:
State
— Region
—— Area
The code is provided here in VB and C# and then described in detail below.
NOTE: Be sure to set a reference to System.Core and System.Xml.Linq
In C#:
XElement doc = XElement.Load("testXML.xml");
TreeNode stateNode;
TreeNode regionNode;
foreach (XElement state in doc.Descendants("State"))
{
stateNode = treeView1.Nodes.Add(state.Attribute("name").Value);
foreach (XElement region in state.Descendants("Region"))
{
regionNode =
stateNode.Nodes.Add(region.Attribute("name").Value);
foreach (XElement area in region.Descendants("Area"))
{
regionNode.Nodes.Add(area.Attribute("name").Value);
}
}
}
In VB:
Dim doc As XElement = XElement.Load("testXML.xml")
Dim stateNode As TreeNode
Dim regionNode As TreeNode
For Each state As XElement In doc…<State>
stateNode = TreeView1.Nodes.Add(state.@name)
For Each region As XElement In state…<Region>
regionNode = stateNode.Nodes.Add(region.@name)
For Each area As XElement In region…<Area>
regionNode.Nodes.Add(area.@name)
Next
Next
Next
In both cases, the XML is first retrieved from a file. An in-memory XML string could be used instead.
Three for/each loops are used, one for each level of the TreeView hierarchy.
The states are processed first. A node is added for each state name.
The regions are processed next. A node is added under the state for each region name.
Finally, the areas are processed. A node is added under the region for each area name.
Notice that the VB code leverages XML literals. The C# code uses XElements (which also work in VB).
Enjoy!
Suguresh — March 11, 2013 @ 1:55 am
How can i do the same thing (from XML to tree structure) for dynamically selected XML file, where tag names will be different from each XML file? if i have same parent and child tag or elements in one of the XML file, will it work?