Wrox Home  
Search
Beginning Ajax
by Chris Ullman, Lucinda Dykes
March 2007, Paperback


XML, XSLT, and XPath

XML is another familiar cornerstone, the language that is used to describe and structure data, to any Web developer.

With XML comes a whole plethora of supporting technologies, each allocated its own individual niche. An XML document contains no information about how it should be displayed or searched. Once the data is rendered as an XML document, you typically need other technologies to search and display information from it. IE and Firefox both contain XML engines that can parse XML documents.

XSLT is a language for transforming XML documents into other XML documents. It isn't restricted to transforming XML documents into XML. You could also specify HTML or pure text as the output format. When you transform a document, you start with a source XML document, such as the following fragment:

<HotelList>
  <Hotel>
    <Name>Hotel Shakespeare</Name>
    <Rooms>50</Rooms>
    <City>Birmingham</City>
  </Hotel>
  <Hotel>
    <Name>Hotel Washington</Name>
    <Rooms>500</Rooms>
    <City>Chicago</City>
  </Hotel>
</HotelList>

You apply a second document in XSLT to the first document. The XSLT document contains a set of rules for how the transformation should be conducted, as shown here:

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="/">    
      <table>
     <tr>
          <td>
            Hotel Name
          </td>
          <td>
          Number of Rooms
          </td>
          <td>
          Location
          </td>
     </tr>
        <xsl:for-each select="//Hotel">
        <tr>
          <td>
              <xsl:value-of select="Name" />          
          </td>
          <td>
              <xsl:value-of select="Rooms" />
          </td>
          <td>
              <xsl:value-of select="City" />
          </td>
         </tr>
        </xsl:for-each>
      </table>
  </xsl:template>

</xsl:stylesheet>

And you get a resulting XML document (in this case, also an XHTML document) looking like this:

       <table>
         <tr>
          <td>
            Hotel Name
          </td>
          <td>
          Number of Rooms
          </td>
          <td>
          Location
          </td>
        </tr>
        <tr>
          <td>
              Hotel Shakespeare
          </td>
          <td>
              50
          </td>
          <td>
              Birmingham
          </td>
         </tr>
        <tr>
          <td>
              Hotel Washington
          </td>
          <td>
              500
          </td>
          <td>
              Chicago
          </td>
         </tr>
       </table>

You could then insert the XHTML document fragment into the HTML page dynamically to update the page.

XSLT is another standard maintained by W3C. Both IE and Mozilla have XSLT processors; however, they don't always treat their XSLT documents in the same way. XSLT uses another language, XPath, to query the XML document when applying its transformations. XPath queries are used to address elements within the original XML document, such as the following:

<xsl:for-each select="//Hotel">

The //Hotel statement instructs the browser's XSLT processor to look for elements called <Hotel> that are descendants of the root element <HotelList>. XPath queries can be used to locate specific items or groups of items within an XML document, using a syntax that is superficially similar to the way browsers can locate Web pages, with the following as an example:

//HotelList/Hotel/Rooms

These techniques can be used to retrieve sections of data and display it on the page using the browser. Again, they are able to offer instantaneous updates without the need for a trip back to the server. Both XSLT and XPath are discussed in more detail in Chapter 8 "XSLT and XPath" of Beginning Ajax.

The XMLHttpRequest Object

If there's one thing you haven't come across before, it's likely to be the XMLHttpRequestObject. Microsoft introduced quite an obscure little ActiveX control in Internet Explorer version 5 (IE 5) called the XMLHttp object. Of course, ActiveX controls are tied to IE, so shortly afterward, Mozilla engineers followed suit and created their own version for Mozilla 1 and Netscape 7, the corresponding XMLHttpRequest object. The status of these objects was elevated considerably because of their inclusion in the original Ajax article. They are now more commonly referred to singularly as the XMLHttpRequest object, and, in IE 7, there is a native XMLHttpRequest object in addition to the ActiveX Control. Versions of this object have been included in Safari 1.2 and Opera as well.

But what does it do? Well, it allows a developer to submit and receive XML documents in the background. Previously, you could use hidden frames or IFrames to perform this task for you, but the XMLHttpRequest is rather more sophisticated in the ways in which it allows you to send and pick up data.

Unfortunately, because it isn't yet standard, that means there are still two separate ways of creating it. In versions of IE prior to version 7, it is created as an ActiveXObject in JavaScript as follows:

var xHRObject = new ActiveXObject("Microsoft.XMLHTTP");
There are several versions of the MSXML library with respective ProgIDs to instantiate XMLHttp object. Specifically, you cannot instantiate any version of XMLHttp object higher than 'Msxml2.XMLHTTP.3.0' with the given version independent ProgID Microsoft.XMLHTTP.

In Mozilla Firefox, IE 7, and other browsers, it is created as follows:

var xHRObject = new XMLHttpRequest();

In turn, this means that you have to do a little bit of browser feature detection before you can determine in which way the object needs to be created. Because ActiveX controls and objects are unique to IE, you can test for them by attempting to call the ActiveXObject method of the window object. For IE 7, Mozilla Firefox, Safari, and Opera, there is an XMLHttpRequest method. These calls use implicit type conversion to return true or false, depending on which browser is being used to view the page. In other words, if there is an ActiveXObject on that browser, it will return true. If not, it will return false.

Typically, your browser feature detection and object creation code would look something like this:

var xHRObject = false;
if (window.XMLHttpRequest)
{	
xHRObject = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
xHRObject = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
     //Do something to handle non-Ajax supporting browsers.
}

There are plans to standardize this functionality in level 3 of the DOM specification, but until then, you will need to make allowances for this fact.

The role the XMLHttpRequest object plays is a major one. It is used heavily in Google's Gmail to ferry the data backward and forward behind the scenes. In fact, it can provide the asynchronous part of the Ajax application. It uses the onreadystatechange event to indicate when it has finished loading information. You can tell it to get an XML document as shown here:

xHRObject.open("GET", "SuiteList.xml", true);

Then, at a later point, you can check the value of the readyState property to see if it has finished loading and, if it has, then extract the information that you need.

The XMLHttpRequest object is misleading in one sense, in that you don't have to transfer XML with it. You can quite happily use it to transfer HTML or just plain text back and forth as well. The XMLHttpRequest is examined in more detail in Chapter 4, "Ajax Techniques," of Beginning Ajax. The difference between synchronous and asynchronous methods of data transfer is examined in Chapter 1, "Introducing Ajax."

This article is adapted from Chapter 1, "Introducing Ajax," of the book Beginning Ajax (Wrox, 2007, ISBN: 978-0-470-10675-4), by Chris Ullman and Lucinda Dykes. Chris Ullman is a freelance Web developer and technical author who has spent many years working with ASP/ASP.NET. Coming from a computer science background, he started initially as a UNIX/Linux guru, who gravitated toward Microsoft technologies). He cut his teeth on Wrox Press ASP guides, and has since written and contributed to more than 25 books, most notably as lead author for Wrox's bestselling Beginning ASP/ASP.NET 1.x series. He has contributed chapters to books on PHP, ColdFusion, JavaScript, Web Services, C#, XML, and other Internet-related technologies. After he left Wrox as a full-time employee in August 2001, he branched out into VB.NET/C# programming and ASP.NET development, and he started his own business, CUASP Consulting Ltd, in April 2003.

Page 1 | Page 2