Xml TreeView

The application shown here was my firstadventure into Xml in the .Net platform. My goal was to be able toreflect any Xml file into the Windows Forms TreeView control. I foundvarious examples online, but none I found were suited for opening allXml files, rather they were suited to one schema or another.

The problem I ran into while writing this was more of a programmingtheory issue than a coding issue. This example deals with two instancesof recursion, one for reading the Xml file in and one for adding thedata correctly to the TreeView control. I am aware that thisapplication reinvents the wheel, since Internet Explorer gives theexact same functionality, but I was more interested in learning how towork with Xml files within the .Net Platform, especially using theXmlDocument class and this seemed like a good start.

The following code snippet shows the method I used to accomplish my goal.

private void FillTree(XmlNode node, TreeNodeCollection parentnode)
{
// End recursion if the node is a text type
if(node == null || node.NodeType == XmlNodeType.Text || node.NodeType == XmlNodeType.CDATA)
return;

TreeNodeCollection tmptreenodecollection = AddNodeToTree(node, parentnode);

// Add all the children of the current node to the treeview
foreach(XmlNode tmpchildnode in node.ChildNodes)
{
FillTree(tmpchildnode, tmptreenodecollection);
}
}

private TreeNodeCollection AddNodeToTree(XmlNode node, TreeNodeCollection parentnode)
{
TreeNode newchildnode = CreateTreeNodeFromXmlNode(node);

// if nothing to add, return the parent item
if(newchildnode == null) return parentnode;

// add the newly created tree node to its parent
if(parentnode != null) parentnode.Add(newchildnode);

return newchildnode.Nodes;
}

private TreeNode CreateTreeNodeFromXmlNode(XmlNode node)
{
TreeNode tmptreenode = new TreeNode();

if((node.HasChildNodes) && (node.FirstChild.Value != null))
{
tmptreenode = new TreeNode(node.Name);
TreeNode tmptreenode2 = new TreeNode(node.FirstChild.Value);
tmptreenode.Nodes.Add(tmptreenode2);
}
else if(node.NodeType != XmlNodeType.CDATA)
{
tmptreenode = new TreeNode(node.Name);
}

return tmptreenode;
}

image1 Xml TreeView

About the Author: James Divine(james@4divine.com) is a Senior Software Developer with over 12 yearsexperience working with web programming, desktop applicationprogramming, server application programming and handheld deviceprogramming. He has been working in .Net and C# for more than twoyears. James currently holds a Microsoft Certified Professionalcertification and is working towards the MCSD.

Related Articles :

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!