asp:Feature
LANGUAGES: C#
ASP.NET VERSIONS: 2.0
New XML Features in .NET Version 2: Part III
XML Data Binding
By Dan Wahlin
Version 2 of the .NET Framework provides several new enhancements that make it easier than ever for developers to parse, validate, transform, and bind XML data. Part I of this series demonstrated how to parse XML using new methods found in the XmlReader class and how XML data can be generated using the XmlWriter class. Part II focused on editing XML loaded into memory and validating it using the XmlDocument and XPathNavigator classes. Part II also showed how to perform more efficient XSLT transformations using the new XslCompiledTransform class.
In this final article in the series you ll be introduced to several new controls available in ASP.NET 2.0 that simplify working with XML. You ll see how to use the XmlDataSource data source control to bind data to different ASP.NET server controls and be introduced to the TreeView control. Before moving ahead to the new XML features found in version 2, it s worthwhile to take a quick look at how XML data binding occurred in .NET 1.1.
XML Data Binding in .NET 1.1
The simplest way to bind XML to server controls in .NET 1.1 was to load an XML document into an XmlDataDocument class and then convert it to a DataSet or simply load a document directly into a DataSet using the ReadXml method. An example of using ReadXml to bind RSS data to a DataList control named dlRss is shown in Figure 1.
DataSet ds = new DataSet();
ds.ReadXml("http://msdn.microsoft.com/rss.xml");
//RSS items will be placed into the 3rd DataTable
dlRss.DataSource = ds.Tables[2].DefaultView;
dlRss.DataBind();
Figure 1: Loading XML data into a DataSet using the ReadXml method.
If you re new to RSS, Figure 2 shows a simple example of
an RSS 2.0 document. Notice that details about an article are marked up using
an
http://www.xmlforasp.net/XML/RssGenerator.aspx/
Figure 2: RSS
documents allow different types of items to be marked up using
Once an RSS document such as the one shown in Figure 2 is loaded into a DataSet, the appropriate columns in the DataTable must be bound to the target server control. An example of creating a DataList control ItemTemplate that binds to link and title columns is shown here:
<%# DataBinder.Eval(Container.DataItem,"title") %>
Although this approach doesn t require a lot of code, it does
requires you to think of the XML data in a relational manner (rows and columns)
rather than hierarchically. It also makes locating the data you want from the
original RSS document a little tricky because you need to know which DataTable
contains the RSS
If the RSS data being bound to the DataList control needs to be filtered, you ll need to use the DataView class RowFilter property rather than filtering with a simple XPath expression. An example of filtering out RSS items that don t have the word XML in the title is shown in Figure 3.
DataSet ds = new DataSet();
ds.ReadXml("http://msdn.microsoft.com/rss.xml");
DataView view = ds.Tables[2].DefaultView;
view.RowFilter = "title LIKE '%XML%'";
DataList1.DataSource = view;
DataList1.DataBind();
Figure 3: Filtering XML data using the DataView class RowFilter property.
This type of code certainly works and is fairly simple to write but it doesn t allow you to leverage XML technologies to their full extent and requires more code than should really be necessary for such a simple task. Let s look at how to eliminate this code completely using new classes available in version 2 of the .NET Framework.
Using the XmlDataSource Control
ASP.NET version 2 contains several data source controls that are designed to interact with different types of data sources without writing VB.NET or C# code. Data source controls included in .NET version 2 include SqlDataSource, ObjectDataSource, AccessDataSource, XmlDataSource, and SiteMapDataSource. The XmlDataSource control derives from a new class named HierarchicalDataSourceControl and can be used to bind XML documents to different ASP.NET server controls, such as the DataList, TreeView, and Menu controls. It can also be used to bind data to controls normally used with relational data, such as the GridView and DataList controls.
Adding an XmlDataSource control to an ASP.NET Web Form is
done by using the
DataSourceID="RSSDataSource"> ...DataList templates
DataFile="http://msdn.microsoft.com/rss.xml" XPath="rss/channel/item" /> Figure 4: Binding
an XmlDataSource data source control to a DataList control. Binding data contained within the XmlDataSource control
can be done by using the DataList s new DataSourceID property, as shown in
Figure 4. At run time, the DataList will locate the XmlDataSource control based
on its ID, and automatically bind the data. You may be wondering how the DataList knows what data to
output as it binds to the XmlDataSource control. The XmlDataSource s XPath
property identifies which nodes to bind ( DataSourceID="RSSDataSource">
href='<%#
XPath("link") %>'> <%#
XPath("title") %> DataFile="http://msdn.microsoft.com/rss.xml" XPath="rss/channel/item" /> Figure 5: Binding
to nodes within an XML document can be done using the new XPath data binding
expression. Using this expression causes the XPathBinder class to be invoked. The <%# XPath(expression) %> syntax invokes a new
framework class called XPathBinder that automatically locates the target nodes
using the supplied XPath expression and accesses their associated data. Figure
4 demonstrates how to bind the and Filtering out unwanted RSS items can easily be
accomplished by changing the XmlDataSource control s XPath property. No
additional VB.NET or C# code has to be written. XPath allows where clauses
(officially called predicates) to be
written so that you can effectively tell the XmlDataSource to Find all DataFile="http://msdn.microsoft.com/rss.xml" XPath="rss/channel/item[contains(title,'XML')]" EnableCaching="true" CacheDuration="300" CacheExpirationPolicy="Sliding" /> In addition to showing how to use an XPath predicate, this
example also demonstrates how XML data can be cached by the XmlDataSource
control. In this case, the data will be cached for 300 seconds because it s
unlikely that the feed will change that frequently. This increases the
scalability of the application and makes it load faster for the end user. The
XmlDataSource s EnableCaching property is True by default and the CacheDuration
property defaults to a value of 0 (infinite cache that only expires when the
source file changes). Because this example references an external URL rather
than a local file, a specific CacheDuration is listed so that the RSS data is
grabbed every 300 seconds. While XML data can be bound to relational controls such as
the DataList, many types of XML documents may need to be shown in a
hierarchical manner within an ASP.NET Web Form. Fortunately, ASP.NET 2.0
contains two new server controls named Menu and TreeView that make it easy to
show nested XML data to end users while writing little to no VB.NET or C# code. The TreeView control that ships with .NET version 2 allows
hierarchical XML data to be displayed in a standard tree format. A TreeView
control consists of multiple TreeNode objects that represent the hierarchical data
shown to the end user. TreeNodes can be hard-coded into a TreeView control
using a When binding a TreeView to an XmlDataSource control, it s
important to identify which nodes in the XML document contain the data used to
create TreeNode objects. For example, if you wanted to bind the
element s name and href attributes shown in Figure 7, you would need to create
data bindings within the TreeView control to let it know which nodes to bind
and which nodes to ignore. This type of data binding is done by using a Figure 8 shows an example of binding a TreeView to an
XmlDataSource control. Notice that it defines two data bindings to the XML
document shown in Figure 7. The first binding identifies that the XML document s
root element should be bound to the starting node of the TreeView control. This
is done by setting the DataMember property of the TreeNodeBinding object to links .
The second binding causes the TreeView to bind to all elements in
the XML document. This is done by setting the DataMember property to link . The
TextField property identifies the name of the XML node that provides the text
for each TreeNode object created in the TreeView, while the NavigateUrlField
identifies which XML node to use for TreeNode hyperlinks.
href="http://msdn.microsoft.com/asp.net" />
href="http://msdn.microsoft.com/netframework" />
href="http://msdn.microsoft.com/xml" />
href="http://msdn.microsoft.com/webservices" /> Figure 7: An XML
document containing link data. DataSourceID="MenuItemsDataSource" AutoGenerateDataBindings="False" ImageSet="XPFileExplorer" NodeIndent="15"> DataMember="links" /> DataMember="link" NavigateUrlField="href" /> Font-Names="Tahoma"
Font-Size="8pt" HorizontalPadding="2"
ForeColor="#000000" /> ForeColor="#6666AA" /> DataFile="~/XML/Links.xml" XPath="links"
/> Figure 8: Identifying
XML nodes that should be bound to a TreeView control is accomplished by using
TreeNodeBinding tags. The TreeView control is quite flexible when it comes to
changing the look and feel of TreeNode objects. In addition to being able to
customize node styles, you can also control the images that appear as the
TreeView is rendered. The control ships with several default image sets that
define what images are shown next to each TreeNode object. Figure 8 shows an
example of different image sets that are defined using the TreeView s ImageSet
property. The image sets shown in Figure 9 include XPFileExplorer, Contacts,
and BulletedList2. Binding different types of XML documents to ASP.NET server
controls has been greatly simplified in .NET version 2. With the introduction
of the XmlDataSource data source control, XML binding can be done without
writing a single line of code. XML data can also be filtered using XPath
expressions, which allows fine-grained control over which data shows up in your
ASP.NET Web Forms. In a future article I ll introduce additional controls, such
as SiteMapDataSource, that can be used to bind XML data to server controls. If you didn t get a chance to read Part
I or Part
II, or would like to see more information about the topics covered in this
article, visit http://www.xmlforasp.net
to view online video tutorials that discuss various .NET version 2 XML
technologies. The sample code
accompanying this article is available for download. Dan Wahlin
(Microsoft Most Valuable Professional for ASP.NET and XML Web services) is
president of Wahlin Consulting, as well as a .NET instructor at Interface
Technical Training. Dan founded the XML for ASP.NET Developers Web site (http://www.XMLforASP.NET), which focuses
on using XML, ADO.NET, and Web services in Microsoft s .NET platform. He s also
on the INETA Speaker s Bureau and speaks to .NET User Groups around the US.
Dan co-authored Professional Windows DNA
(Wrox), ASP.NET: Tips, Tutorials, and Code
(SAMS), and ASP.NET 1.1 Insider Solutions
(SAMS), and authored XML for ASP.NET Developers
(SAMS).
Figure 6: The HTML output shown here
is generated by binding a DataList to an XmlDataSource control loaded with RSS
data. Binding the XmlDataSource Control to Server Controls
Figure 9: The TreeView control can
be customized and themed to make it fit into your ASP.NET 2.0 Web site. The
TreeView controls shown here have different values assigned to the ImageSet
property. Conclusion