Most of the source code is self explanatory, however let's
dive into some details:
ASPX
Listing 2 – TreeView Control
<asp:TreeView ID="xmlTreeView" runat="server"
AutoGenerateDataBindings="true"
OnSelectedNodeChanged="xmlTreeView_SelectedNodeChanged">
<DataBindings>
<asp:TreeNodeBinding DataMember="Book" ValueField="Id" ImageUrl="~/Images/add.png" />
</DataBindings>
<LeafNodeStyle ImageUrl="~/Images/leaf.png" />
<RootNodeStyle ImageUrl="~/Images/add.png" />
<ParentNodeStyle ImageUrl="~/Images/action_forward.gif" />
</asp:TreeView>
AutoGenerateDataBindings property of
the TreeView is enabled. This tells the control to generate the tree node
bindings automatically from the DataSource.
DataBindings Section defines how the
fields of hierarchical data items are mapped to TreeNode properties. Here I
have bound the Node "Book" using TreeNodeBinding.
The ValueField is given as the "Id" attribute
of the Book Node. This is very important as this ValueField
is used to generate the DataPath of the SelectedNode and helps to uniquely
identify each node.
You can also change the appearance of the Tree Node by
providing Images to the ImageUrl property.
Other properties like LeafNodeStyle,
RootNodeStyle, ParentNodeStyle etc are pretty self explanatory.
Code Behind(C#)
protected void xmlTreeView_SelectedNodeChanged(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath(Session["CurrentXMLFile"].ToString()));
XmlNode node = doc.SelectSingleNode(xmlTreeView.SelectedNode.DataPath);
txtEditXML.Text = node.InnerXml;
Session["CurrentEditXpath"] = xmlTreeView.SelectedNode.DataPath;
}
In the SelectedNodeChanged event, we
load an XmlDocument using the same XML file and identify the node using the SelectedNode.DataPath property of the TreeView Control. The
InnerXml is loaded to the Text box for editing. The DataPath is preserved in
the Session state to use when the node is saved.
Restrictions
A restriction of this approach is that in the XML file, each
node must be uniquely identifiable. Otherwise the Xpath approach won't work.