XML in ASP.NET 2.0


Most Microsoft-focused Web developers have usually relied on either Microsoft SQL Server or Microsoft Access for their data storage needs. Today, however, a considerable amount of data is stored in XML format, so considerable inroads have been made toward improving Microsoft's core Web technology to work easily with this format.

The XmlDataSource Server Control

ASP.NET 2.0 introduced a series of data source controls to bridge the gap between your data stores (such as XML) and the data-bound controls at your disposal. These new data controls not only enable you to retrieve data from various data stores, but they also let you easily manipulate the data (using paging, sorting, editing, and filtering) before the data is bound to an ASP.NET server control.

With XML being as important as it is, a specific data source control has been added to ASP.NET 2.0 just for retrieving and working with XML data. The XmlDataSource control enables you to connect to your XML data and to use this data with any of the ASP.NET data-bound controls. Just like the SqlDataSource and the ObjectDataSource controls (which are some of the other data source controls), the XmlDataSource control also enables you not only to retrieve data, but also to insert, delete, and update data items. With the world turning more and more to XML data formats, such as Web services, RSS feeds, and more, this control is a valuable resource for your Web applications.

To show the XmlDataSource control in action, first create a simple XML file and include this file in your application. Listing 15-19 shows a simple XML file of Russian painters that you can use.

Listing 15-19: Painters.xml

image from book
      <?xml version="1.0" encoding="utf-8" ?>      <Artists>         <Painter name="Vasily Kandinsky">            <Painting>               <Title>Composition No. 218</Title>               <Year>1919</Year>            </Painting>          </Painter>          <Painter name="Pavel Filonov">            <Painting>               <Title>Formula of Spring</Title>               <Year>1929</Year>            </Painting>          </Painter>          <Painter name="Pyotr Konchalovsky">            <Painting>               <Title>Sorrento Garden</Title>               <Year>1924</Year>           </Painting>         </Painter>      </Artists> 
image from book

Now that the Painters.xml file is in place, the next step is to use an ASP.NET DataList control and to connect this DataList control to an <asp:XmlDataSource> control. This is illustrated in Listing 15-20.

Listing 15-20: Using a DataList control to display XML content

image from book
      <%@ Page Language="C#"%>      <html xmlns="http://www.w3.org/1999/xhtml" >      <head runat="server">          <title>XmlDataSource</title>       </head>      <body>          <form  runat="server">              <asp:DataList  Runat="server" DataSource>                  <ItemTemplate>                     <p><%# XPath("@name") %><br />                     <%# XPath("Painting/Title") %><br />                     <%# XPath("Painting/Year") %></p>                  </ItemTemplate>              </asp:DataList>              <asp:XmlDataSource  Runat="server"               DataFile="~/Painters.xml" XPath="Artists/Painter">              </asp:XmlDataSource>          </form>      </body>      </html> 
image from book

This is a simple example, but it shows you the power and ease of using the XmlDataSource control. You should pay attention to only two attributes in this example. The first is the DataFile attribute. This attribute points to the location of the XML file. Because the file resides in the root directory of the application, it is simply ~/Painters.xml. The next attribute included in the XmlDataSource control is the XPath attribute. The XmlDataSource control uses XPath for the filtering of XML data. In this case, the XmlDataSource control is taking everything within the <Painter> set of elements. The value Artists/Painter means that the XmlDataSource control navigates to the <Artists> element and then to the <Painter> element within the specified XML file.

The DataList control next must specify the DataSourceID as the XmlDataSource control. In the <ItemTemplate> section of the DataList control, you can retrieve specific values from the XML file by using XPath commands. The XPath commands filter the data from the XML file. The first value retrieved is an element attribute (name) that is contained in the <Painter> element. If you are retrieving an attribute of an element, you preface the name of the attribute with an @ symbol. In this case then, you simply specify @name to get at the painter's name. The next two XPath commands go deeper into the XML file and get the specific painting and the year of the painting. Remember to separate nodes with a /. When run in the browser, this code produces the results illustrated in Figure 15-13.

image from book
Figure 15-13

Besides working from static XML files like the Painters.xml file shown earlier, the XmlDataSource file has the capability to work from dynamic, URL-accessible XML files. One popular XML format that is pervasive on the Internet today is the blog or weblog. Blogs, or personal diaries, can be viewed in the browser, through an RSS-aggregator, or just as pure XML.

As you look at my blog in Figure 15-14, you can see the XML it produces directly in the browser. (You can find a lot of blogs to play with for this example at weblogs.asp.net.)

image from book
Figure 15-14

Now that you know the location of the XML from the blog, you can use this XML with the XmlDataSource control and display some of the results in a DataList control. The code for this example is shown in Listing 15-21.

Listing 15-21: Working with an RSS feed

image from book
            <%@ Page Language="C#"%>      <html xmlns="http://www.w3.org/1999/xhtml" >      <head runat="server">          <title>XmlDataSource</title>      </head>      <body>          <form  runat="server">              <asp:DataList  Runat="server" DataSource>                  <HeaderTemplate>                     <table border="1" cellpadding="3">                  </HeaderTemplate>                  <ItemTemplate>                     <tr><td><%# XPath("title") %><br />                     <%# XPath("pubDate") %><br />                     <%# XPath("description") %></td></tr>                  </ItemTemplate>                  <AlternatingItemTemplate>                     <tr bgcolor="LightGrey"><td><%# XPath("title") %><br />                     <%# XPath("pubDate") %><br />                     <%# XPath("description") %></td></tr>                  </AlternatingItemTemplate>                  <FooterTemplate>                     </table>                  </FooterTemplate>              </asp:DataList>              <asp:XmlDataSource  Runat="server"               DataFile="http://geekswithblogs.net/evjen/Rss.aspx"               XPath="rss/channel/item">              </asp:XmlDataSource>          </form>      </body>      </html> 
image from book

Looking at the code in Listing 15-21, you can see that the DataFile points to a URL where the XML is retrieved. The XPath property filters out all the <item> elements from the RSS feed. The DataList control creates an HTML table and pulls out specific data elements from the RSS feed, such as the <title>, <pubDate>, and <description> elements.

Running this page in the browser, you get something similar to the results shown in Figure 15-15.

image from book
Figure 15-15

This approach also works with XML Web services, even ones for which you can pass in parameters using HTTP-GET. You just set up the DataFile value in the following manner:

      DataFile="http://www.someserver.com/GetWeather.asmx/ZipWeather?zipcode=63301" 

The XmlDataSource Control's Namespace Problem

One big issue with the XmlDataSource control is that when you are using the XPath capabilities of the control, it is unable to understand namespace qualified XML. The XmlDataSource control chokes on any XML data that contain namespaces and, for this reason, it is important to yank out any prefixes and namespaces that are contained in the XML.

To make this a bit easier, the XmlDataSource control includes the attribute TransformFile. This attribute applies your XSLT transform file to the XML pulled from the XmlDataSource control. That means you can use an XSLT transform file to transform your XML so that the prefixes and namespaces are completely removed from the overall XML document. An example of this XSLT document is illustrated in Listing 15-22.

Listing 15-22: Building an XSLT document which removes all prefixes and namespaces

image from book
            <?xml version="1.0" encoding="UTF-8"?>      <xsl:stylesheet version="1.0"        xmlns:xsl="http://www.w3.org/1999/XSL/Transform">         <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>         <xsl:template match="*">            <!-- Remove any prefixes -->            <xsl:element name="{local-name()}">                <!-- Work through attributes -->                <xsl:for-each select="@*">                  <!-- Remove any attribute prefixes -->                  <xsl:attribute name="{local-name()}">                     <xsl:value-of select="."/>                  </xsl:attribute>                </xsl:for-each>           <xsl:apply-templates/>            </xsl:element>         </xsl:template>      </xsl:stylesheet> 
image from book

Now with this XSLT document in place within your application, you can use the XmlDataSource control to pull XML data and to strip that data of any prefixes and namespaces.

      <asp:XmlDataSource  runat="server"        DataFile="NamespaceFilled.xml" TransformFile="~/RemoveNamespace.xsl"        XPath="ItemLookupResponse/Items/Item"></asp:XmlDataSource> 

The Xml Server Control

Since the very beginning of ASP.NET, there has always been a server control called the Xml server control. This control performs the simple operation of XSLT transformation upon an XML document. This control is rather easy to use. All you do is point to the XML file you wish to transform using the DocumentSource attribute and indicate the XSLT transform file using the TransformSource attribute.

To see this in action, use the Painters.xml file that was shown in Listing 15-19. The next step is to create your XSLT transform file. The process is shown in Listing 15-23.

Listing 15-23: The XSLT transformation file

image from book
      <?xml version="1.0" encoding="utf-8"?>      <xsl:stylesheet version="1.0"          xmlns:xsl="http://www.w3.org/1999/XSL/Transform">          <xsl:template match="/">            <html>            <body>              <h3>List of Painters &amp; Paintings</h3>              <table border="1">                 <tr bgcolor="LightGrey">                  <th>Name</th>                  <th>Painting</th>                  <th>Year</th>                </tr>                <xsl:apply-templates select="//Painter"/>              </table>            </body>          </html>          </xsl:template>          <xsl:template match="Painter">          <tr>            <td>              <xsl:value-of select="@name"/>            </td>            <td>              <xsl:value-of select="Painting/Title"/>            </td>            <td>              <xsl:value-of select="Painting/Year"/>            </td>          </tr>        </xsl:template>     </xsl:stylesheet> 
image from book

With the XML document and the XSLT document in place, the final step is to combine the two using the Xml server control provided by ASP.NET. This is illustrated in Listing 15-24.

Listing 15-24: Combining the XML and XSLT documents using the Xml server control

image from book
      <%@ Page Language="C#" %>      <html xmlns="http://www.w3.org/1999/xhtml" >      <head  runat="server">          <title>XmlDataSource</title>      </head>      <body>          <form  runat="server">              <asp:Xml  runat="server" DocumentSource="~/Painters.xml"               TransformSource="~/PaintersTransform.xsl"></asp:Xml>          </form>      </body>      </html> 
image from book

The end result is shown in Figure 15-16.

image from book
Figure 15-16




Professional XML
Professional XML (Programmer to Programmer)
ISBN: 0471777773
EAN: 2147483647
Year: 2004
Pages: 215

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net