Skip to main content
photo
 
Transforming Content with XSL

Let's look at the XSL stylesheet to see how it transforms and presents an XML document. The first thing to understand about an XSL file is that it does not contain any data. It contains instructions on how to select and present the data from an XML file. But how does an XML file know which XSL stylesheet to use? It's quite simple actually. In the opening lines of an XML document, you include a processing instruction that links to the stylesheet. Figure 7 displays these processing instructions (<?xml-stylesheet ...?>) for different browsers. In this example, the XML file would use the "gateways_ss.xsl," "gateways_ss_ie.xsl," or "gateways_ss_lynx.xsl" stylesheet depending on the client browser. The "media=" parameter at the end of each line is a Cocoon feature that performs automatic browser detection and directs users to the appropriate stylesheet for their browsers.

Figure 7. Connecting XML and XSL Files
		
<?xml version="1.0" ?&gt;
<!-- Specify the media type and the corresponding stylesheet

<?xml-stylesheet href="gateways_ss.xsl" 
  type="text/xsl" media="netscape"?>
<?xml-stylesheet href="gateways_ss_ie.xsl" 
  type="text/xsl" media="explorer"?>
<?xml-stylesheet href="gateways_ss.xsl" 
  type="text/xsl" media="mozilla5"?>
<?xml-stylesheet href="gateways_ss_lynx.xsl" 
  type="text/xsl" media="lynx"?>
<?xml-stylesheet href="gateways_ss.xsl" 
  type="text/xsl"?>
The XSL file then uses "templates" to identify the content to select from the XML file and specify how to format that content. A "template" corresponds to the tags in the XML document. For example, if you look back to the sample XSL file in Figure 2, you'll see it has templates for "book," "title," `author" and so on that correspond to the tags in the original XML document. The XSL file is selecting the content within those tags and formatting it with the HTML tags within its "<xsl:template match>" tags. This XSL file is styling the content for display as an HTML page in a browser. Different browser types may have different stylesheets if you choose to design for different browsers. A PDF output would also have a different stylesheet. But all the stylesheets use the same source XML document.

This significantly simplifies content management because it enables you to make changes to only one content file and make no changes to the stylesheets because the content is totally separated from the presentation.

Figure 8 illustrates how these XML/XSL transformations occur within the Cocoon publishing framework. An XML file is processed on the server by a "parser" that analyzes and validates the XML tags. It then uses the XSL stylesheets to transform the XML document into the appropriate output format for the clients (PDF or HTML).

Figure 8. Transforming XML Documents into XHTML and PDF

Figure 8. Transforming XML Documents into XHTML and PDF