[quoted text, click to view] "Casper JH Erasmus" <ceit@mweb.co.za> wrote in message news:KPmdnZ_XbbRYwqnfRVn-jg@is.co.za...
> How do I save the contents of a TreeView to a XML Document?
Like any WinForms control, you've probably found XmlSerialization won't cut it because
of references to IntPtrs (in this case).
When you're only interested in preserving the node hierarchy of the TreeView, then the
most direct means is by traversing the nodes in the TreeNodeCollections and adding
XmlElements to an XmlDocument as you go (they align with one another quite elegantly.)
Here's an example that does that to save off the contents of a TreeView control,
treeView1, to an .xml file (by way of an XmlDocument). Similar logic can be done
to populate a TreeView from an .xml file; the schema of the .xml file is an entirely
arbitrary choice.
- - - SaveTreeNodeCollection.cs (excerpt)
using System;
using System.IO;
using System.Windows.Forms;
using System.Xml;
// . . .
private void SaveNode( XmlElement eNodes, TreeNodeCollection tnc)
{
foreach( TreeNode n in tnc)
this.SaveNode( eNodes, n);
}
private void SaveNode( XmlElement eNodes, TreeNode n )
{
XmlDocument nodeFactory = eNodes.OwnerDocument;
XmlElement child = nodeFactory.CreateElement( "Node");
XmlAttribute text = nodeFactory.CreateAttribute( "Text");
text.Value = n.Text;
child.Attributes.Append( text);
if ( null != n.Nodes && n.Nodes.Count > 0 )
{
XmlElement grandchildren = nodeFactory.CreateElement( "Nodes");
child.AppendChild( grandchildren);
this.SaveNode( grandchildren, n.Nodes);
}
eNodes.AppendChild( child);
}
private void btnSave_Click(object sender, System.EventArgs e)
{
XmlDocument doc = new XmlDocument( );
XmlElement eDoc = doc.CreateElement( "TreeView");
if ( null != this.treeView1.Nodes && this.treeView1.Nodes.Count > 0 )
{
XmlElement eNodes = doc.CreateElement( "Nodes");
this.SaveNode( eNodes, this.treeView1.Nodes);
eDoc.AppendChild( eNodes);
}
doc.AppendChild( eDoc);
XmlTextWriter sink = new XmlTextWriter( "../../tree.xml", System.Text.Encoding.UTF8);
try
{
doc.WriteTo( sink);
sink.Flush( );
}
finally
{
sink.Close( );
}
}
// . . .
- - -
If you need more than just the Text property of each TreeNode saved (for example, its
Selected and/or Expanded states, or its associated image) then it's straightforward to add
the requisite XmlAttributes to the simple implementation shown here.
Derek Harmon