Accessing and Updating Data in ASP.NET 2.0: Retrieving XML Data with XmlDataSource Control
By Scott Mitchell
A Multipart Series on ASP.NET 2.0's Data Source Controls
ASP.NET 2.0 introduced a number of new Web controls designed for accessing and modifying data.
These controls allow page developers to declaratively access and modify data without writing any
code to perform the data access. This article is one in a series of articles on ASP.NET 2.0's new data
source controls.
Data Source Control Basics - explores the concepts
and advantages of data source controls, and compares their usage in ASP.NET 2.0 to data access techniques in ASP.NET 1.x.
Accessing Database Data - shows how to use the
SqlDataSource and AccessDataSource controls to query data from a relational database.
Filtering Database Data with Parameters - learn how to
retrieve just a subset of database data based on hard-coded values and values from the querystring, other Web controls on the page,
session variables, and so on.
Creating Custom Parameter Controls - learn how
to create your own custom, declarative Parameter controls for use in the data source controls' parameters collections.
Inserting Data - learn how to insert data using
a SqlDataSource control. Also examines how to retrieve the IDENTITY column value for the just-inserted record.
Deleting Data - see how to delete data using
a SqlDataSource control. Also looks at how to programmatically cancel a delete.
Updating Basics - learn the basics of updating database data using a
SqlDataSource control. Also examines using the GridView to provide a web-based editing interface.
Customizing the Editing Interface - see how to
customize the GridView's columns to provide a customized editing interface that includes input validation and alternative
user interface elements.
Handling Database NULL Valuese - explore how to
extend the GridView's customized editing interface to handle database NULL values.
Introduction
With its new declarative data source controls and improved data Web controls, ASP.NET
2.0 has greatly simplified the process of working with data. In Part 2 of this article series,
Accessing Database Data, we looked at how to use the
SqlDataSource control to retrieve data from a relational database, which could then be bound to any data Web control (such
as the GridView, DetailsView,
FormView, DataList, Repeater, and so on). XML data can be accessed (and displayed) just as easily with the XmlDataSource
control.
The XmlDataSource control makes accessing, filtering, and transforming XML data a simple, code-free process. Additionally,
the XPath() and XPathSelect() databinding methods added to ASP.NET 2.0 make displaying particular
XML values or binding entire XML nodesets just as easy. And the XML data accessed can be from a local file or automatically
downloaded from a specified URL.
In this article we will examine how to use the XmlDataSource control and the XPath() and XPathSelect()
databinding methods, displaying the results in a variety of data Web controls. Read on to learn more!
XmlDataSource Basics
The XmlDataSource control exists merely as a proxy for retrieving XML data, which can then be programmatically accessed or
bound to a data Web control. To access XML data from an ASP.NET page using the XmlDataSource control, start by dragging the
control from the Toolbox onto the Designer (the XmlDataSource control is found in the Data section of the Toolbox). From
the XmlDataSource's smart tag, click the "Configure Data Source" link to bring up the Configure Data Source wizard (shown below).
From the wizard, you can set the XmlDataSource control's three most useful properties:
DataFile -
specifies the file that contains the XML data to access. This can be a local file, like ~/App_Data/XMLFile.xml,
or a remote file, like http://msdn.microsoft.com/rss.xml.
TransformFile -
XML documents can be transformed from one structure to another using a markup language known as XSL Transformations,
or XSLT. If you want to transform the XML contents in DataFile before working with the XML data, specify the
XSLT file to perform the transformation here. For more information on XSLT, check out the XSLT Tutorial
at W3 Schools.
XPath -
XPath is an XML syntax used to filter the contents of an XML document, returning a particular value or nodeset. If you want
to work with a particular set of XML data, specify an XPath expression here to limit the results. See W3 School's
XPath tutorial for more information.
If you do not have the XML data or XSLT saved in a file, you can specify the raw XML or XSLT directly through the XmlDataSource's
Data and
Transform properties.
These properties cannot be set through the Configure Data Source wizard, but instead must be set through the Properties window.
(Click on the XmlDataSource control in the Designer and hit F4.)
Binding the XmlDataSource Control to a Data Web Control and Accessing Particular XML Data
Once you've configured the XmlDataSource control, add a data Web control to the page and set its DataSourceID
property to the ID of the XmlDataSource control (a task that can easily be done through the drop-down list in the
data Web control's smart tag). ASP.NET 2.0 offers two new databinding methods for accessing a particular value or noteset from
the XML data bound to the data Web control:
XPath("xpath") - accesses a particular value. To retrieve the text value of a node, simply
refer to the node in the xpath; for an attribute, prefix the attribute name with @.
XPathSelect("xpath") - returns a nodeset. Can be used to bind a set of nodes to a nested
data Web control.
These databinding statements must appear within a template. For controls like the GridView and DetailsView, which
are composed of fields (like BoundFields, CheckBoxFields, and so on), use TemplateFields for each field you want to display.
Example 1: Displaying a Remote RSS 2.0 Feed in a DataList
RSS, or Really Simple Syndication, is an XML format designed to allow website content to be easily
syndicated. The syndicated content can be integrated into other websites, or can be viewed by individuals via an assortment
of desktop applications. Many sites syndicate content today using RSS 2.0. For example, the latest 4Guys articles are
syndicated at http://aspnet.4guysfromrolla.com/rss/rss.aspx.
An RSS syndication feed has a format similar to the following:
<rss version="2.0">
<channel>
<title>News by Scott</title>
<link>http://www.example.com</link>
<description>Hear the news from Scott.</description>
<item>
<title>Exercise to Stay Fit</title>
<link>http://www.example.com/news.aspx?Id=4</link>
<description>
Doctors are currently studying whether exercise improves
physical fitness. The results are expected in 2009.
</description>
<pubDate>Wed, 20 Sep 2006 03:15:00 GMT</pubDate>
</item>
<item>
<title>(Still) War in the Middle East</title>
<link>http://www.example.com/news.aspx?Id=2</link>
<description>
Historians remain baffled that turmoil in the Middle East
still reigns. Is it time for both sides to shake hands
and make up?
</description>
<pubDate>Tue, 19 Sep 2006 06:31:15 GMT</pubDate>
</item>
...
</channel>
</rss>
In short, an RSS feed is made up of a set of <item> elements, each of which represents some recent, syndicated
piece of content. For more information on RSS and the benefits of syndicating content, check out
Syndicating Your Web Site's Content with RSS; also consult
the RSS 2.0 Specification.
For this example, we want to bind the set of content items to a DataList. Therefore, set the XmlDataSource control's
DataFile property to the URL of the remote RSS 2.0 feed source (such as http://aspnet.4guysfromrolla.com/rss/rss.aspx)
and the XPath property to /rss/channel/item. This XPath statement instructs the XmlDataSource
to return the set of <item> elements, meaning the DataList bound to this XmlDataSource will have one
record created for each <item> element in the specified RSS feed.
Next, add the DataList and configure its ItemTemplate to display the <title>,
<description>, and <pubDate> of each content item, along with a link to read the content
(using the <link> element's value). The following markup will work:
Note how the <# XPath("xpath") %> syntax is used to grab a particular value from the current
node bound to the DataList. Since the DataList is bound to a set of <item> nodes, <%# XPath("link") %>
will return the value of the current <item> node's <link> element.
After specifying the ItemTemplate, take a moment to view the page in a browser. The following screenshot shows
the output for the 4Guys RSS feed.
Example 2: Binding a Nodeset to a Nested Data Web Control
The XPath("xpath") method allows us to bind a particular value relative from the current XML node, but what
if we want to get back an entire nodeset and bind that to a nested data Web control? The XPathSelect("xpath")
method provides this functionality. To illustrate the use of this method, let's create an example that displays a receipt for
a user's purchase, where the purchase details are spelled out in an XML format. In the download available at the end of
this article you'll find a file named PO.xml in the project's App_Data folder. This XML file
(whose primary structure was found online in this
example XML file) contains information about a single order, and has the following structure:
To display a receipt, we need to display the customer's information, the subtotal, tax, and total, and the set of items
ordered. Since there can be a variable number of items, this can best be displayed by using a nested data Web control that's
bound to the set of <Item> nodes.
To display the customer and price details, add a FormView and bind it to a new XmlDataSource whose DataFile property
set to ~/App_Data/PO.xml. Do not bother setting the XPath property. Next, in the FormView's
ItemTemplate, use the XPath("xpath") method to display the the customer and price details:
Since the XmlDataSource control does not have an XPath value specified, the <Order> node is
what is bound to the FormView. Therefore, to get the <Name> element value from the <Customer>
node, we need to use the XPath statement /Order/Customer/Name. To get an attribute value - orderDate,
an attribute in the <Order> element - prefix the attribute name with @ (i.e., /Order/@orderDate).
The above databinding syntax displays the customer and price details in the FormView. We still need to display the set of
<Item>s associated with this order. To accomplish this, add a GridView control within the FormView's
ItemTemplate and assign its DataSource property to the set of <Item> nodes using the
following syntax: <asp:GridView runat="server" ... DataSource='<# XPathSelect("/Order/Manifest/Item") %>' ...>.
Then, in the GridView's <Columns> section, add a TemplateField for each of the item details to display:
Conclusion
ASP.NET 2.0 offers a number of different data source controls for working with different types of data. The SqlDataSource control,
for example, is designed to work with data in a relational database. As we saw in this article, to work with XML data, use
the XmlDataSource control. The XmlDataSource control can access local or remote XML files, or can have raw XML data assigned to
its Data property. There's also the optional TransformFile and XPath properties that
can be set to transform or filter the contents of the XML data.
Once the XmlDataSource control has been properly configured, it can be bound to a data Web control. The contents of the XML
returned by the XmlDataSource control can be retrieved as scalar values using XPath("xpath") or as
nodesets using XPathSelect("xpath"). See the download available at the end of this article for the
complete code explored in the two examples above.
A Multipart Series on ASP.NET 2.0's Data Source Controls
ASP.NET 2.0 introduced a number of new Web controls designed for accessing and modifying data.
These controls allow page developers to declaratively access and modify data without writing any
code to perform the data access. This article is one in a series of articles on ASP.NET 2.0's new data
source controls.
Data Source Control Basics - explores the concepts
and advantages of data source controls, and compares their usage in ASP.NET 2.0 to data access techniques in ASP.NET 1.x.
Accessing Database Data - shows how to use the
SqlDataSource and AccessDataSource controls to query data from a relational database.
Filtering Database Data with Parameters - learn how to
retrieve just a subset of database data based on hard-coded values and values from the querystring, other Web controls on the page,
session variables, and so on.
Creating Custom Parameter Controls - learn how
to create your own custom, declarative Parameter controls for use in the data source controls' parameters collections.
Inserting Data - learn how to insert data using
a SqlDataSource control. Also examines how to retrieve the IDENTITY column value for the just-inserted record.
Deleting Data - see how to delete data using
a SqlDataSource control. Also looks at how to programmatically cancel a delete.
Updating Basics - learn the basics of updating database data using a
SqlDataSource control. Also examines using the GridView to provide a web-based editing interface.
Customizing the Editing Interface - see how to
customize the GridView's columns to provide a customized editing interface that includes input validation and alternative
user interface elements.
Handling Database NULL Valuese - explore how to
extend the GridView's customized editing interface to handle database NULL values.