Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Save a TreeView into an XML File

0.00/5 (No votes)
24 Jul 2013 1  
The article includes a sample project showing how to save the nodes of a TreeView into an XML file.

Sample Image - treeviewexport.jpg

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.

License

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