06 March 2009

Populating WPF TreeView with xml file in c#?

This wil help you to populate a Wpf UI control form a complex hielerichal xml file

recursive call for adding nodes
-----------------------------------
private void addTreeNode(XmlNode xmlNode, TreeViewItem treeNode)
{
XmlNode xNode;
TreeViewItem tNode;
XmlNodeList xNodeList;
if (xmlNode.HasChildNodes) //The current node has children
{
xNodeList = xmlNode.ChildNodes;
for (int x = 0; x <= xNodeList.Count - 1; x++)
//Loop through the child nodes
{
xNode = xmlNode.ChildNodes[x];
int i = treeNode.Items.Add(new TreeViewItem() { Header = xNode.Name });
tNode = treeNode.Items[x] as TreeViewItem;
addTreeNode(xNode, tNode);
}
}
else //No children, so add the outer xml (trimming off whitespace)
treeNode.Header = xmlNode.OuterXml.Trim();
}

-------------------------------------------------------------------------------------
try
{
//Just a good practice -- change the cursor to a
//wait cursor while the nodes populate
this.Cursor = Cursors.Wait;
//First, we'll load the Xml document
XmlDocument xDoc = new XmlDocument();
xDoc.Load(dlg.FileName);
//Now, clear out the treeview,
//and add the first (root) node
myTreeView.Items.Clear();
TreeViewItem nodeToAdd = new TreeViewItem();
nodeToAdd.Header = xDoc.DocumentElement.Name;
myTreeView.Items.Add(nodeToAdd);
TreeViewItem tNode = new TreeViewItem();
tNode = (TreeViewItem)myTreeView.Items[0];
//We make a call to addTreeNode,
//where we'll add all of our nodes
addTreeNode(xDoc.DocumentElement, tNode);
foreach (TreeViewItem item in myTreeView.Items)
{
item.IsExpanded = true;
}
this.Cursor = Cursors.Arrow;
}
catch
{
throw;
}