Reading Back the Persisted Nodes
No matter which XML format you prefer, the code for reading the XML file and populating the TreeView control with the persisted nodes is the same, thanks to the functionality of the DOMDocument class. The Click
event code for the Load Nodes
button starts by creating a DOMDocument object and loading the XML file created by one of the Save
buttons (you can change the code to prompt the user to select the file to be loaded). After loading the file successfully, the code iterates through its nodes with the GetElementsByTagName
method, extracts each node's Caption
attribute values, and adds a new item to the TreeView control, setting its properties to the attribute values contained in the XML element. (See Listing 6
You retrieve each <NODE>
element in the XML document using the following statement:
Then the code calls the GetAttribute method of the newElement variable to retrieve the ParentKey, Key and Caption attributes, recreate the node and place it on the control. Each node automatically appears under its parent node (as long as the parent nodes are added to the control before their child nodes), because the code sets the ParentKey property to the proper parent when it creates the node.
As you've seen, extending the TreeView control to support editing, dragging and dropping nodes, and persistance isn't particularly difficult. Adding these features lets you use the native TreeView control where you might otherwise need to use a custom control.