Accessing and Updating Data in ASP.NET: Retrieving XML Data with XmlDataSource Control

时间:2014-04-30 19:04:56   收藏:0   阅读:727

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:

mamicode.com,码迷

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:

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:

< 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.

mamicode.com,码迷

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>
  <Manifest>     <Item>       <ID>ID</ID>       <Title>title</Title>       <Quantity>qty</Quantity>       <UnitPrice>price</UnitPrice>     </Item>     <Item>       <ID>ID</ID>       <Title>title</Title>       <Quantity>qty</Quantity>       <UnitPrice>price</UnitPrice>     </Item>     ...   </Manifest>
  <Receipt>     <Subtotal>subtotal</Subtotal>     <Tax>tax</Tax>     <Total>grand total</Total>   </Receipt> < /Order>

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>
    ... Items GridView to go here! ...
    <p style="border-bottom:solid 1px black;">       <b>Subtotal:</b> <asp:Label runat="server" ID="SubtotalLabel" Text=‘<%#XPath("/Order/Receipt/Subtotal")%>‘></asp:Label><br />       <b>Tax:</b> <asp:Label runat="server" ID="TaxLabel" Text=‘<%#XPath("/Order/Receipt/Tax")%>‘></asp:Label><br />     </p>     <p>       <b>Total:</b> <asp:Label runat="server" ID="TotalLabel" Text=‘<%#XPath("/Order/Receipt/Total")%>‘></asp:Label><br />     </p>   </ItemTemplate> < /asp:FormView>

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>     ...
    <asp:GridView runat="server" ID="ItemsSummary" DataSource=‘<%# XPathSelect("/Order/Manifest/Item") %>‘           AutoGenerateColumns="False">       <Columns>         <asp:TemplateField HeaderText="Title">           <ItemTemplate>             <asp:Label runat="server" ID="NameLabel" Text=‘<%#XPath("Title")%>‘></asp:Label>           </ItemTemplate>         </asp:TemplateField>         <asp:TemplateField HeaderText="Qty" ItemStyle-HorizontalAlign="Right">           <ItemTemplate>             <asp:Label runat="server" ID="QuantityLabel" Text=‘<%#XPath("Quantity")%>‘></asp:Label>           </ItemTemplate>         </asp:TemplateField>         <asp:TemplateField HeaderText="Unit Price" ItemStyle-HorizontalAlign="Right">           <ItemTemplate>             <asp:Label runat="server" ID="UnitPriceLabel" Text=‘<%#XPath("UnitPrice")%>‘></asp:Label>           </ItemTemplate>         </asp:TemplateField>       </Columns>     </asp:GridView>
    ...   </ItemTemplate> < /asp:FormView>
mamicode.com,码迷

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!

Accessing and Updating Data in ASP.NET: Retrieving XML Data with XmlDataSource Control,码迷,mamicode.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!