XML DataSource Controls in .NET 2.0

As noted in previous columns, .NET 2.0 pushes most of ADO.NET into the frameworks level, and provides you with various DataSource controls to make accessing data easy. With the XML DataSource control, you can bind to an XML document just as easily as you bind to tables in a database. If the XML document you load is hierarchical, the data is exposed hierarchically, which makes it ideal to map an XML document to a TreeView control.

To get started, fire up Visual Studio 2005 (or Visual Web Developer) and create
a new web site named BindingToXML. Create a new item, an XML file named BookList.xml,
and add it to the project, as shown in Example 1:

Add an XMLDataSource to your Default.aspx page. You can do this by dragging
one onto your form from the Toolbox, or, interestingly, by dragging one from
the Toolbox right into the Source view. Add an attribute, DataFile, and set its
value to the name of your XML file, as shown in Figure 1:

Figure 1.

You are now ready to add a TreeView control and bind it to this data source. Switch to design mode and drag a TreeView control onto the form. (The TreeView control is usually found under the Navigation section of the toolbox.)

The smart tag allows you to choose the XMLDataSource you just created as the TreeView's data source.

Figure 2.

Click on Auto Format in the smart tag, and choose Windows Help as the format style, as shown in Figure 3:

Figure 3.

Click on Edit TreeNode Databindings to open the TreeView DataBindingsEditor. Set the DataMember for each member in the hierarchy that you want to display (in this case, book, Author, and Publisher), and set the TextField to tell the TreeView which text to use for each DataMember, as shown in Figure 4:

Note that for each binding, the DataMember corresponds to the DataBinding you added (book, Publisher, Author) and the TextField corresponds to the value you placed in the TextField property, which in turn corresponds to the AttributeName in the XML.

Run the application and the data in the XML document is bound to the control, as shown in Figure 5:

Figure 5.

You can easily modify how the tree is displayed by choosing a different scheme in AutoFormat. For example, if you choose MSDN, the books are replaced by the MSDN minus and plus signs. In either mode, each entry is a link, as shown in Figure 6: