
Introduction
It is sometimes useful to export a TreeView object. You can use this to populate the TreeView next time you start the application and so on. This article will show how to implement this feature.
Please note that I am not using the System.Xml namespace because the file is built dynamically during the used recursive function, and because of speed.
How to do
First, we read the root element of the TreeView in our method exportToXml(). Using the root element, we call the method parseNode(). This is a recursive function which parses every node.
private static void parseNode(TreeNode tn)
{
IEnumerator ie = tn.Nodes.GetEnumerator();
string parentnode = "";
parentnode = tn.Text;
while (ie.MoveNext())
{
TreeNode ctn = (TreeNode) ie.Current;
if (ctn.GetNodeCount(true) == 0)
{
sr.Write(ctn.Text);
}
else
{
sr.Write("<" + ctn.Text + ">");
}
if (ctn.GetNodeCount(true) > 0)
{
parseNode(ctn);
}
}
sr.Write("</" + parentnode + ">");
sr.WriteLine("");
}
For receiving all nodes, we use enumerators. The enumerators contain the nodes and we iterate through to receive the names and the values. Please note that the variable sr is a StreamReader object which I use to write the XML data into a file. This variable is defined outside of this method.
How to use the code
Have a look at the sample-code to see how to use the class TreeViewToXml.
This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be found here