Accessing and Updating Data in ASP.NET: Retrieving XML Data with XmlDataSource Control
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, likehttp://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 inDataFile
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> |
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:
< asp:DataList ID="FeedList" runat="server" DataSourceID="RSSFeedDataSource"> <ItemTemplate> <h4> <a href='<%# XPath("link") %>'> <asp:Label runat="server" ID="TitleLabel" Text='<%# XPath("title") %>'></asp:Label> </a> </h4> <p> <i>Published <%#XPath("pubDate")%></i> </p> <p> <asp:Label runat="server" ID="DescriptionLabel" Text='<%# XPath("description") %>'></asp:Label> </p> <p> [<a href='<%# XPath("link") %>'>Read More</a>] </p> <br /> </ItemTemplate> < /asp:DataList> |
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.
An even easier approach to displaying RSS feeds in a web page is to use my free, open-source RssFeed control! See A Custom ASP.NET Server Control for Displaying RSS Feeds for more information...
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:
< Order orderDate="orderDate"> <Customer> <Name>name</Name> <Cardnum>credit card number</Cardnum> </Customer> |
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:
< asp:FormView ID="Receipt" runat="server" DataSourceID="PODataSource"> <ItemTemplate> <p><h3>RECEIPT</h3></p> <p><b>Order Date:</b> <asp:Label runat="server" ID="OrderDateLabel" Text='<%#XPath("/Order/@orderDate")%>'></asp:Label></p> <p> <b><u>Customer Details:</u></b><br /> <b>Name:</b> <asp:Label runat="server" ID="NameLabel" Text='<%#XPath("/Order/Customer/Name")%>'></asp:Label><br /> <b>Card #:</b> <asp:Label runat="server" ID="CardNumberLabel" Text='<%#XPath("/Order/Customer/Cardnum")%>'></asp:Label><br /> </p> |
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:
< asp:FormView ID="Receipt" runat="server" DataSourceID="PODataSource"> <ItemTemplate> ... |
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.
Happy Programming!