The XmlDataSource Control
Unlike the DataSetDataSource control, the XmlDataSource control is suitable for binding to XML documents that do not have a structure similar to that of a dataset. Consider the RSS document in Figure 16
, saved as MSDN.xml in the project.
|Figure 16. The RSS Document: The XMLDataSource control lets you manage poorly formed XML.|
|Figure 17. The Mighty DataList: Bind the DataList control to the XmlDataSource control.|
Drag-and-drop an XmlDataSource control onto the page and click on the 'Configure Data Source…' link in the Smart Tag. In the Configure Data Source window, set the Data file as "~/MSDN.xml." In the XPath Expression, set it as "rss/channel/item." The purpose of the XPath expression is to set a filter for the XML document so that only a subset of the document is returned. Now drag-and-drop a DataList control onto the page and bind it to XmlDataSource1 (see Figure 17
In the Smart Tag, choose 'Auto Format…' and select the Slate scheme. Now, switch to Source view and add the bold portion of the source code sample below:
<asp:DataList ID="DataList1" Runat="server"
BorderWidth="1px" BackColor="White" CellPadding="3"
<a href='<%#XPath("link")%>'>Link</a><br />
That's it! Press F5 to load the page. You will now be able to see the DataList control displaying a subset of the RSS document (see Figure 18
). And you've just written an RSS reader without writing a single line of code!
|Figure 18. An RSS Reader: Thanks to the XMLDataSource control you can build a dynamic RSS feed without any coding at all.|
If you are feeling adventurous, try loading the RSS document dynamically at runtime, allowing the user to choose which news feed they want to see. To do that, add a TextBox and Button control to the page (see Figure 19
To load the XML document dynamically, code the Load button as follows:
Sub btnLoad_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
XmlDataSource1.DataFile = txtURL.Text
You can now change the news feed dynamically!
In this article, you have seen how to use the various data source controls in ASP.NET 2.0 to connect to various data sources (and not just databases). The data source controls can save you from writing tons of code for data access. You can now declaratively connect to your data sources.