asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search










Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

Distributing Server Load to the Client with XML and XSL
By Ian Vink
Rating: 4.0 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article

    Introduction

    Your Web server has a tough job. It must connect to databases, retrieve data, process it, format it into HTML, and then send it to the client. Increase the life of your server by reducing the load on it using XML and XSL. The eXtensible Stylesheet Language (or XML) is a style-sheet format for XML documents that is the counterpart to the Cascading Style Sheet (CSS) in HTML. By sending the XML and XSL to the client, and having the client create the HTML for you, your server can spend time doing other things, like processing credit card orders!

    Requirements

    Server and client should have the XML parser, version 3 from http://msdn.Microsoft.com/xml. The client should have IE 5 or higher.

    Overview

    An ASP page will connect to a database and retrieve the data. Then it will be converted into XML and sent to the client. The ASP page will associate an XSL URL in the data stream it sends to the client, and the XSL will have a CSS associated with it as well. Once the client receives the XML and fetches the associated XSL and CSS, the client will transform the XML into HTML.

    To simplify the code, we won't be using error checking, but you should use it in your production applications.

    Step 1: Retrieve The Data from a Database

    In this example we'll be using an Access database with simple customer data.

    Here's the full ASP code:

    <%@ Language=VBScript %>
    <% option explicit %>
    
    <%
        Response.ContentType = "text/xml"
        Response.Write "<?xml version='1.0' ?>" 
        Response.Write "<?xml-stylesheet type='text/xsl' href='report.xsl'?>"
    
        dim RS, CN
        set CN = server.CreateObject("adodb.connection")
        set RS = server.CreateObject("adodb.recordset")
        
        CN.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & server.MapPath("sales.mdb")
        CN.Open
        
        RS.Open "select first, last, phone, email from sales order by last",cn
         
        Response.Write "<ROOT>"
           Response.Write RS2XML(RS,"CUSTOMER")         
        Response.Write "</ROOT>"
        
        CN.close
        set rs = nothing
        set cn = nothing
        
        
    function RS2XML(rs, ChildNode)
        
        dim Field
    	if rs is nothing then exit function
    	 
    	ChildNode = ucase(ChildNode)
    	 
    	if rs.eof then 
    	    RS2XML = ""
    	    exit function
    	 end if  
    
    		do until rs.eof
    			if ChildNode <> "" then RS2XML = RS2XML & "<" & ChildNode & ">"
    			for each field in rs.fields
    			   RS2XML = RS2XML & " <" & ucase(field.name) & 
    ">" & server.HTMLEncode(NotNull(field.value)) & "</" & ucase(field.name) & ">" next if ChildNode <> "" then RS2XML = RS2XML & "</" & ChildNode & ">" rs.movenext loop end function Function NotNull(vOrig) If(IsNull(vOrig)) then NotNull = "" else NotNull = vOrig end if End Function %>

    Code Analysis for Step 1

    Response.ContentType = "text/xml"
    Response.Write "<?xml version='1.0' ?>" 
    Response.Write "<?xml-stylesheet type='text/xsl' href='report.xsl'?>"
    
    This tells the browser that once it gets the text, it should be treated as if it's XML data with an associated XSL style sheet. Remove these three lines to debug the output. When ASP generates errors, it writes code to your Response stream. So if the browser is expecting XML and gets error messages, it won't show the error to you.

    In order to see the XML in native format, omit the line containing "report.xsl." Your XML will be then transformed into HTML using IE's native XSL. It'll look like this:

        dim RS, CN
        set CN = server.CreateObject("adodb.connection")
        set RS = server.CreateObject("adodb.recordset")
        
    CN.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & server.MapPath("sales.mdb")
        CN.Open
        
        RS.Open "select first, last, phone, email from sales order by last",cn
         
    This gets the recordset from the database. In this case it is sales data for a report.
        Response.Write "<ROOT>"
           Response.Write RS2XML(RS,"CUSTOMER")         
        Response.Write "</ROOT>"
    
    This is the heart of the ASP page. We write out a ROOT node for the XML document. It can be called anything you wish, but ROOT serves to illustrate the point. Then we pass the recordset to a generic function that converts recordsets into XML. You can save the contents of a recordset into XML format, however, we use this function to show how you can control the type of XML output.

    Now that the ASP page has written XML data and XML headers to the client, the client will transform the XML into HTML using the style sheet indicated at the top of the ASP page.

    Step 2: Using XSL to Transform XML into HTML on the Client

    The XSL style sheet tells the browser how to transform the XML into HTML. Here's the complete code.

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
    <xsl:template match="/">
    <HTML>
    <HEAD>
    <LINK rel="stylesheet" type="text/css" href="general.css"/>
    </HEAD>
    <BODY>      
            
    <TABLE class="tblResults">
      <CAPTION class="title">Customers</CAPTION>
      <TR>
          <TD class="Header">Name:</TD>
          <TD class="Header">E-Mail:</TD>
          <TD class="Header">Phone:</TD>
      </TR>    
      <xsl:for-each select="ROOT/CUSTOMER">
        <TR>
          <TD class="Data">
               <xsl:value-of select="FIRST"/>
               <xsl:value-of select="LAST"/>
          </TD>
          <TD class="Data">
             <A>
                <xsl:attribute name="href">mailto:<xsl:value-of select="EMAIL"/></xsl:attribute>
                <xsl:value-of select="EMAIL"/>
             </A>   
          </TD>
          <TD class="Data"><xsl:value-of select="PHONE"/></TD>
        </TR>
       </xsl:for-each>  
    </TABLE>   
    
    </BODY>
    </HTML>
    </xsl:template>
    </xsl:stylesheet>
    

    Code Analysis for Step 2

    Notice that the XML looks a lot like HTML. The XSL is simply interspersed into the HTML; it acts exactly like a mail merge, in fact. The HTML must be well formed. All tags must have case-sensitive closing tags, and tags that normally don't have closing tags, like the line break (BR) tag, should look like this <BR/> with the trailing /.

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
    <xsl:template match="/">
    <HTML>
    <HEAD>
    <LINK rel="stylesheet" type="text/css" href="general.css"/>
    </HEAD>
    <BODY>      
    
    This code tells the browser the file is a standard XSL style sheet and that it will use the Cascading Style Sheet called general.css to handle look and feel.
    <TABLE class="tblResults">
      <CAPTION class="title">Customers</CAPTION>
      <TR>
          <TD class="Header">Name:</TD>
          <TD class="Header">E-Mail:</TD>
          <TD class="Header">Phone:</TD>
      </TR>    
      <xsl:for-each select="ROOT/CUSTOMER">
        <TR>
          <TD class="Data">
               <xsl:value-of select="FIRST"/>
               <xsl:value-of select="LAST"/>
          </TD>
          <TD class="Data">
             <A>
                <xsl:attribute name="href">mailto:<xsl:value-of select="EMAIL"/></xsl:attribute>
                <xsl:value-of select="EMAIL"/>
             </A>   
          </TD>
          <TD class="Data"><xsl:value-of select="PHONE"/></TD>
        </TR>
       </xsl:for-each>  
    </TABLE>   
    
    This section is where the table is created. The main loop happens inside the table after the first row is written. The first row contains the titles of the columns. The loop is controlled by an XSL for-next command. The XML is output using the XSL value-of command.

    One interesting part is the XSL attribute command. Use it to add the attribute H_REF to the anchor tag, "A," so that the e-mail address becomes clickable.

    </BODY>
    </HTML>
    </xsl:template>
    </xsl:stylesheet>
    
    The document ends up with the last tags being closed.

    When rendered, the table will look like this:

    Final Notes

    The ASP page in this example can now act as an XML data provider. You can even specify it as the source of an XML data island <xml src="default.asp"></xml> or provide XML for other on-line applications in a Business to Business (B2B) solution. Remember the server doesn't always have to produce the HTML output; the client can do that work for you.

    About the Author

    Ian Vink is a Canadian who has worked all over the world in the IT sector, most recently in Haifa, Israel. He has been an intranet Webmaster for four years and has been writing code since 1982. He's taught computer technology since 1994 and owns a number of Web stores. He's married to a wonderful Australian Oracle designer. Please send comments or questions to Ian at ian@ianvink.com.

  • Rate This Article
    Not HelpfulMost Helpful
    1 2 3 4 5
    Supporting Products/Tools
    Stonebroom.ASP2XML
    Stonebroom.ASP2XML(c) is an interface component designed to make building applications that transport data in XML format much easier. It can be used to automatically pass updates back to the original data source.
    [Top]
    Other Articles
    Sep 22, 2005 - Implementing Remote Calling Without Using AJAX
    Right now the latest buzzword around town is AJAX. AJAX is an acronym for Asynchronous JavaScript and XML and is a method used to implement remote calling. The problem is that AJAX is only implemented in ASP.NET 2.0. This article will show you one way to implement remote calling without using AJAX or the XMLHttpRequest object. The technique outlined can even be used from classic ASP and is sufficient for most remote calling needs.
    [Read This Article]  [Top]
    Aug 18, 2005 - SQL Server 2005 XQuery and XML-DML - Part 3
    This article is the third and final installment of Alex Homer's series covering the new XML support in Microsoft SQL Server 2005. In it he covers updating the contents of xml columns, comparing traditional XML update techniques with XQuery, and using XQuery in a managed code stored procedure.
    [Read This Article]  [Top]
    Aug 11, 2005 - SQL Server 2005 XQuery and XML-DML - Part 2
    In the second part of his series on SQL Server 2005's new XML support, Alex Homer looks at extracting data from XML columns, comparing traditional XML data access approaches with XQuery, and combining XQuery and XSL-T.
    [Read This Article]  [Top]
    Aug 3, 2005 - SQL Server 2005 XQuery and XML-DML - Part 1
    Microsoft SQL Server 2005 now offers great support for and close integration with XML as a data persistence format. In the first article of his series examining this new support, Alex Homer offers an overview of how SQL Server 2005 stores XML documents and schemas, examines how it supports querying and manipulating XML documents, and provides a simple test application that allows you to experiment with XQuery.
    [Read This Article]  [Top]
    Jun 30, 2005 - Reading and Writing XML in .NET Version 2.0 - Part 3, Cont'd
    In the final article of his series on reading and writing XML in .NET 2.0, Alex Homer looks at how the updated XML document store objects XmlDocument, XmlDataDocument and PathDocument can be used to read, persist and write XML documents and fragments more easily and more efficiently than in .NET 1.x.
    [Read This Article]  [Top]
    Jun 29, 2005 - Reading and Writing XML in .NET Version 2.0 - Part 3
    In the final article of his series on reading and writing XML in .NET 2.0, Alex Homer looks at how the updated XML document store objects XmlDocument, XmlDataDocument and PathDocument can be used to read, persist and write XML documents and fragments more easily and more efficiently than in .NET 1.x.
    [Read This Article]  [Top]
    Jun 16, 2005 - Reading and Writing XML in .NET Version 2.0 - Part 2, Cont'd
    Alex Homer continues his series on reading and writing XML in .NET 2.0. In part one, we focused on the reading side of things, examining the XmlReader and XmlReaderSettings classes. In this article, we move on to look at the XmlWriter and XmlWriterSettings classes, and how they can be used to write XML documents and fragments more easily and more efficiently than in version 1.x of .NET.
    [Read This Article]  [Top]
    Jun 15, 2005 - Reading and Writing XML in .NET Version 2.0 - Part 2
    Alex Homer continues his series on reading and writing XML in .NET 2.0. In part one, we focused on the reading side of things, examining the XmlReader and XmlReaderSettings classes. In this article, we move on to look at the XmlWriter and XmlWriterSettings classes, and how they can be used to write XML documents and fragments more easily and more efficiently than in version 1.x of .NET.
    [Read This Article]  [Top]
    Jun 2, 2005 - Reading and Writing XML in .NET Version 2.0 - Part 1, Cont'd
    In the first part of his series on reading and writing XML in .NET 2.0, Alex Homer discusses the XmlReader and XmlReaderSettings classes. The XmlReader exposes several useful new features and the all new XmlReaderSettings class makes it easy to generate single or multiple instances of an XmlReader with a range of useful properties.
    [Read This Article]  [Top]
    Jun 1, 2005 - Reading and Writing XML in .NET Version 2.0 - Part 1
    In the first part of his series on reading and writing XML in .NET 2.0, Alex Homer discusses the XmlReader and XmlReaderSettings classes. The XmlReader exposes several useful new features and the all new XmlReaderSettings class makes it easy to generate single or multiple instances of an XmlReader with a range of useful properties.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry



    JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers