Using XSLT for Presentation


For many people, reading XML borders on the impossible . Using XSLT can remedy the problem to a great extent, by telling a browser or application how to interpret the information the XML file contains. Presentation can mean everything once you get past the requirements of accurate data. Unfortunately, creating Web pages by hand to achieve a combination of great presentation and accurate data consumes a lot of time, so Webmasters have looked for an easier way to create a presentation online. The combination of XML (data) and XSLT (presentation) has become more than a convenience for many organizations. Using this technique helps companies create accurate presentations with little effort. Because Google Web Services relies on XML, XSLT also provides one of the best ways for you to create a great presentation. The following sections provide a good overview of XSLT. You'll also find a section with references to other XSLT information sources.

Using a Script to Call an XSLT Page

Google doesn't know how you want to present the data they provide, so the XML you receive doesn't include any form of XSLT declaration. This declaration appears as <?xmlstylesheet type= " text/xsl " href= " SearchDisplay.xsl " ?> in the XML file. The href attribute tells where to find the XSLT file. Without this information, the browser will never display anything but XML on screen. It would seem that the situation is hopeless. However, you have other options, such as writing a script that performs the transformation process using another technique.

The example in Listing 3.2 shows how you can download a response from Google, store the information locally, and translate it using XSLT. The result is the same as modifying the XML file to include the required linkage information, but far more automatic. You'll find the complete source for this example in the \Chapter 03\Viewing XSLT folder of the source code located on the Sybex Web site.

Listing 3.2: Performing a Transformation in JavaScript
start example
 function GetData(XslFile)   {      // Get the search data.      var TheResult = CallGoogle();      // Place the resulting information in an XML document.      var ProcDoc = new ActiveXObject("Msxml2.DOMDocument.4.0");      ProcDoc.async = false;      ProcDoc.loadXML(TheResult.context.xml);      // Create an XSLT document and load the transform into it.      var XSLTData = new ActiveXObject("Msxml2.DOMDocument.4.0");      XSLTData.async = false;      XSLTData.load(XslFile);      // Display the output on screen.      document.write(ProcDoc.transformNode(XSLTData));   } 
end example
 

Before the script can do anything, it must obtain the search results from Google. When using Google Web Services, you must rely on SOAP to perform this task. SOAP is extremely flexible, so you can use a number of techniques to make a request with it. The "Performing a Simple SOAP Call" section of the chapter shows one such technique. All you need to know, for the moment, is that the script obtains search results from Google using the CallGoogle() function.

The next step is a little tricky and definitely Windows specific. The code creates an instance of the Microsoft XML component. The ActiveXObject() function performs this task. The Msxml2.DOMDocument.4.0 string identifies the component. You might have to use Msxml2.DOMDocument.5.0 on newer machines with Microsoft Office 2003 or another new product loaded ”the last part of the string identifies the component version number. Setting the async property to false is important because you don't want the call to load the XML to return until the browser actually receives this file. Finally, the ProcDoc.loadXML() function loads the response from Google Web Services. Notice that the code uses the loadXML() function to load text formatted as XML, rather than XML from a file.

Note  

Most versions of MSXML work fine for this example. However, you'll probably want to get MSXML Version 4.0 from http://msdn.microsoft.com/library/en-us/xmlsdk/htm/sdk_intro_6g53.asp. (MSXML Version 5.0 isn't available for download as of this writing.) The 5.0 version includes a number of features that make working with XML documents a lot easier. In addition, you'll find that the latest versions are slightly faster and contain a number of bug fixes that make your application more reliable.

The code now has a local copy of the data from Google. This local copy will disappear as soon as the function ends, so you don't have to worry about update requirements, but it's important to understand that the copy resides in memory on your machine somewhere.

At this point, the code has data to work with, but no XSLT file. The next step loads the XSLT file defined by the XslFile variable. Notice that the code uses the XSLTData.load() function because the XML appears in a file that the application must load into memory. The coupling between the XML response and the XSLT occurs in the XMLData.transformNode() function call. This call produces output that the document.write() function then sends to the current page. The result is that you see the transformed XML on screen, as shown in Figure 3.9. Notice that the URL doesn't change, even though the content differs , because you're still theoretically on the same Web page.

click to expand
Figure 3.9: The results of using a script to transform XML data received from Google.

Understanding How XSLT Works

Unlike an XML file, an XSLT file generates some type of presentation, using information from the XML file as input. Consequently, XSLT (or simply XSL) files often contain a combination of output text and XML. In fact, all XSLT files begin with the usual header and the special XSLT header shown here.

 <?xml version="1.0" encoding="UTF-8"?>   <xsl:stylesheet version="1.0"   xmlns:xsl="http://www.w3.org/1999/XSL/Transform"   xmlns:fo="http://www.w3.org/1999/XSL/Format"> 

Remember that the <?xml?> element tells the XML parser that this is an XML file. The next element is an XSLT processing instruction. It tells the XML parser that this is an XSLT derivative of an XML file and it includes namespace pointers to Web sites that describe how to interpret XSLT. This instruction is important because otherwise the XML parser looks at this file as XML and won't have a clue what to do with all those XSLT instructions it contains.

An XSLT document describes how to transform an XML document into readable form. Therefore, the first thing it must do is tell the XML parser how much of the XML document to use for the transformation. You can choose anything from just one or two lines of the document to the entire document. Normally, XSLT documents are concerned with an entire XML document, so you'll see a line such as <xsl:template match= / > somewhere in the document.

It's important, at this point, to stress that XSLT doesn't have to output HTML. You can use XSLT to transform XML into anything you want. For example, I recently read an article in Visual Studio magazine where the author uses XSLT to transform XML data into program code. (See the article entitled " Generate.NET Code With XSLT " by Kathleen Dollard at http://www.fawcette.com/vsm/2003_05/magazine/features/dollard/ for details.) That's right ”she stores her coding requirements in XML and generates the required code automatically using XSLT.

Once you define a document as XSLT and define how much of the XML document input you want to process, you begin using a combination of text and XSLT processing instructions to transform the XML into some type of output. The "Writing a Simple XSLT Page" shows a specific example of this transformation.

In general, XSLT is a programming language. One of the most common programming instructions retrieves a value from the XML file. For example, the instruction <xsl:value-of select= " searchQuery " /> retrieves the value of the searchQuery element. However, XSLT doesn't limit you to simply retrieving data from the XML file. You can also use functions, such as the count() function that returns the number of nodes in a result set, to perform data manipulation on the XML input.

You'll also find that XSLT includes a limited number of loop and logic features. For example, you can tell XSLT that you want to perform the same task with every child of the current node using the <xsl:for-each select= ProductInfo/Request/Args/Arg > instruction. In this case, the select attribute tells which node to use for processing purposes.

A final consideration for this book is that XSLT also defines something called an axis. An axis defines a way of looking at the data. For example, the at (@) symbol tells XSLT to look at the attributes of a node, rather than the element. Another common axis is parent, which tells XSLT to look at the parent of the current element.

Writing a Simple XSLT Page

This section describes the XSLT page used with the transformation described in the "Using a Script to Call an XSLT Page" section (see Listing 3.2). Listing 3.3 shows how to create an XSLT page that outputs HTML code. You could use the same technique to create a report or any other form of output based on the XML input received from Google. You'll find the complete source for this example in the \Chapter 03\Viewing XSLT folder of the source code located on the Sybex Web site.

Listing 3.3: Designing an XSLT Page
start example
 <?xml version="1.0" encoding="UTF-8"?>   <xsl:stylesheet version="1.0"         xmlns:xsl="http://www.w3.org/1999/XSL/Transform"         xmlns:fo="http://www.w3.org/1999/XSL/Format">   <xsl:output method="xml" indent="yes"/>   <xsl:template match="/return">   <html>   <head>         <title>XSLT Transformation Example</title>   </head>   <body>        <!-- Display a heading. -->        <h1 align="center">Translated Google Web Services Results</h1>        <!-- Display some common information. -->        <h2>Common Results</h2>        <label>              Search request:              <xsl:value-of select="searchQuery"/>        </label><br/>        ... Other Common Results ...        <!-- Display the search result values. -->        <table align="center" border="1" width="100%">             <caption><h2>Results Returned from Query</h2></caption>             <tbody>                  <tr>                       <th>Site Title</th>                       <th>Snippet</th>                       <th>URL</th>                       <th>Cached Size</th>                  </tr>                  <xsl:for-each select="resultElements/item">                       <tr>                            <td>                                 <xsl:value-of select="title"                                       disable-output-escaping="yes"/>                            </td>                            <td>                                 <xsl:value-of select="snippet"                                       disable-output-escaping="yes"/>                            </td>                            <td>                                 <xsl:text disable-output-escaping="yes">                                       <a href='                                 </xsl:text>                                 <xsl:value-of select="URL"/>                                 <xsl:text disable-output-escaping="yes">                                       '>                                 </xsl:text>                                 <xsl:value-of select="URL"/>                                 <xsl:text disable-output-escaping="yes">                                        </a>                                     </xsl:text>                               </td>                               <td><xsl:value-of select="cachedSize"/></td>                         </tr>                   </xsl:for-each>             </tbody>       </table> </body> </html> </xsl:template> </xsl:stylesheet> 
end example
 

The code begins with the usual declarations. The <xsl:output method= xml indent= yes /> tag is important because it determines the kind of output the parser creates. You can also choose text as the output method or tell the parser that you don't want the output indented. Notice that the code also matches the return element using the <xsl:template match= /return > tag. All of the data appears within this element, so there isn't a good reason to match the root node of the XML document.

The code then outputs the heading. Notice that this is pure HTML and that the code isn't doing anything but outputting this text. The code moves on to the body where it outputs a heading.

The XSLT-specific code begins when the code outputs some of the common information returned by Google. None of this information requires special handling, so the code uses a simple <xsl:value-of select= searchQuery /> tag to retrieve and display the information. The information is surrounded by descriptive text and enclosed within a <label> to make it easier to see.

Each return value requires special handling, so the code relies on a table. Notice the head of the table is standard HTML, but that the next selection is an <xsl:for-each> element. This statement tells the parser to look at all of the children of the resultElements/item node. The system will process each <item> element in turn . The next step is to use the <xsl:value-of> element to retrieve the name and value attributes of each <item> element. Because some of these entries contain the text version of the HTML tags such as &> for the greater than (>) symbol, you must include disable-output-escaping= yes attribute with the <xsl:value-of> element. Otherwise, the code will display the > symbol and not create a tag. The code ends by completing the HTML page, and then completing both the template and the stylesheet.

Learning More about XSLT

This chapter only skims the surface of what you can do with XSLT. You can perform an incredible number of tasks using this technology. One of the better places to learn about XSLT is http://www.w3schools.com/xsl/. You should also view the examples in the XSLT reference at http://www.zvon.org/xxl/XSLTreference/Output/index.html. The XSL reference at http://www.zvon.org/xxl/xslfoReference/Output/index.html can also come in handy when you begin creating complex XSLT pages. You can also find a good tutorial on the Web- monkey site at http://hotwired.lycos.com/webmonkey/98/43/index2a.html?tw=authoring.

Make sure you check out some of the better third party XSLT reference sites. For example, the XSLT.com site at http://xslt.com/ provides links and resources for XSLT from various vendors (not just Microsoft).

It also helps to have some great books on the topic. Make sure you read books such as Mastering XSLT by Chuck White (Sybex, 2002). It also helps to know something about XML schemas, so check out XML Schemas by Chelsea Valentine, Lucinda Dykes, and Ed Tittel (Sybex, 2002).




Mining Google Web Services
Mining Google Web Services: Building Applications with the Google API
ISBN: 0782143334
EAN: 2147483647
Year: 2004
Pages: 157

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