XML in ASP.NET

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

The XmlDataSource Server Control

ASP.NET contains a series of data source controls designed to bridge the gap between your data stores, such as XML, and the data-bound controls at your disposal. These data controls not only enable you to retrieve data from various data stores, they also enable you to 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 is available in ASP.NET just for retrieving and working with XML data: XmlDataSource. This control enables you to connect to your XML data and use this data with any of the ASP.NET data-bound controls. Just like the SqlDataSource and the ObjectDataSource controls, the XmlDataSource control enables you to not only retrieve data, but also insert, delete, and update data items. With increasing numbers of users turning 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. The following code, from the XmlWeb project, reflects a simple XML file of Impressionist painters (code file: painters.xml):

<?xml version="1.0" encoding="utf-8" ?> 
<Artists>
  <Painter name="Claude Monet">
    <Painting>
      <Title>Water Lilies</Title> 
      <Year>1906</Year> 
    </Painting>
  </Painter>
  <Painter name="Edgar Degas">
    <Painting>
      <Title>Blue Dancers</Title> 
      <Year>1899</Year> 
    </Painting>
  </Painter>
  <Painter name="Vincent Van Gogh">
    <Painting>
      <Title>The Starry Night</Title> 
      <Year>1889</Year> 
    </Painting>
  </Painter>
</Artists>

Now that the Painters.xml file is in place, the next step is to use an ASP.NET DataList control and connect this DataList control to an <asp:XmlDataSource> control, as shown here (code file: Default.aspx):

<%@ Page Language="vb" AutoEventWireup="false"
    CodeBehind="Default.aspx.vb" Inherits="XmlWeb._Default" %>
         
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Using XmlDataSource</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DataList ID="PainterList" runat="server"
            DataSourceID="PainterData">
            <ItemTemplate>
                <p>
                    <b>
                        <%# XPath("@name") %></b><br />
                    <i>
                        <%# XPath("Painting/Title") %></i><br />
                    <%# XPath("Painting/Year") %></p>
            </ItemTemplate>
        </asp:DataList>
        <asp:XmlDataSource ID="PainterData" runat="server"
            DataFile="∼/Painters.xml" XPath="Artists/Painter" />
    </div>
    </form>
</body>
</html>

This is a simple example, but it shows you the power and ease of using the XmlDataSource control. Pay attention to two properties in this example. The first is the DataFile property. This property points to the location of the XML file. Because the file resides in the root directory of the Web application, it is simply ∼/Painters.xml. The next property 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) contained in the <Painter> element. When you retrieve an attribute of an element, you preface the name of the attribute with an @ symbol. In this case, you simply specify @name to get the painter's name. The next two XPath commands go deeper into the XML file, getting 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 shown in Figure 8.8.

Figure 8.8 Output for the XmlWeb example

8.8

Besides working from static XML files such as the Painters.xml file, the XmlDataSource file can work from dynamic, URL-accessible XML files. One popular XML format pervasive on the Internet today is blogs, or weblogs. Blogs can be viewed either in the browser (see Figure 8.9), through an RSS aggregator, or just as pure XML.

Figure 8.9 Example output from asp.net weblog

8.9

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, from the ViewRss project, is shown here (code file: Default.aspx):

<%@ Page Language="vb" AutoEventWireup="false"
    CodeBehind="Default.aspx.vb" Inherits="ViewingRss._Default" %>
         
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Viewing RSS</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DataList ID="RssList" runat="server"
            DataSourceID="RssData">
            <HeaderTemplate>
                <table border="1" cellpadding="3">
            </HeaderTemplate>
            <ItemTemplate>
                <tr>
                    <td>
                        <b>
                            <%# XPath("title") %></b><br />
                        <i>
                            <%# "published on " + XPath("pubDate") %></i><br />
                        <%# XPath("description").ToString().Substring(0,100) %>
                    </td>
                </tr>
            </ItemTemplate>
            <AlternatingItemTemplate>
                <tr style="background-color: #e0e0e0;">
                    <td>
                        <b>
                            <%# XPath("title") %></b><br />
                        <i>
                            <%# "published on " + XPath("pubDate") %></i><br />
                        <%# XPath("description").ToString().Substring(0,100) %>
                    </td>
                </tr>
            </AlternatingItemTemplate>
            <FooterTemplate>
                </table>
            </FooterTemplate>
        </asp:DataList>
        <asp:XmlDataSource ID="RssData" runat="server"
            DataFile="http://weblogs.asp.net/mainfeed.aspx"
            XPath="rss/channel/item" />
    </div>
    </form>
</body>
</html>

This example shows 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. To make things a little more visible, only the first 100 characters of each post are displayed.

Running this page in the browser results in something similar to what is shown in Figure 8.10.

Figure 8.10 Output for the Transformation example

8.10

This approach also works with XML Web Services, even those 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 using the XmlDataSource control is that when using the XPath capabilities of the control, it is unable to understand namespace-qualified XML. The XmlDataSource control chokes on any XML data that contains namespaces, so it is important to yank out any prefixes and namespaces contained in the XML.

To make this a bit easier, the XmlDataSource control includes the TransformFile attribute. This attribute takes your XSLT transform file, which can be applied to the XML pulled from the XmlDataSource control. That means you can use an XSLT file, which will transform your XML in such a way that the prefixes and namespaces are completely removed from the overall XML document. An example of this XSLT document is illustrated here:

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

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

<asp:XmlDataSource ID="XmlDataSource1" 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. The control is easy to use: all you do is point to the XML file you wish to transform using the DocumentSource attribute, and the XSLT transform file using the TransformSource attribute. The XmlControl project contains an example to demonstrate this.

To see this in action, use the Painters.xml file shown earlier. Create your XSLT transform file, as shown in the following example (code file: painters.xslt):

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

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 (code file: Default.aspx):

<%@ Page Language="vb" AutoEventWireup="false"
    CodeBehind="Default.aspx.vb" Inherits="XmlControl._Default" %>
         
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
         
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Using the Xml Control</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Xml ID="PainterView" runat="server"
            DocumentSource="∼/Painters.xml"
            TransformSource="∼/painters.xslt" />
    </div>
    </form>
</body>
</html>

The result is shown in Figure 8.11.

Figure 8.11 Output for the XmlControl example

8.11
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset