Using XML and XSLT to Personalize a Web Site Part 2: XSL Transformation Stylesheet BasicsCreating XHTML from XML
As we discussed in the first article, all XSL Transformations are accomplished through the use of templates. The XSL processor (in this case, within the browser) selects a certain section of the original XML; then applies the rules within the template to it, outputting the new content. In this way, the content of a <teaser></teaser> element might be output in a <p></p> tag, and so on. Complex selection and transformation rules can be created, but let's start with the basics.
The most basic XSL style sheet is one that simply takes the original information and outputs it back to the page:
<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <xsl:value-of select="." /></xsl:template> </xsl:stylesheet>
Let's take this apart one line at a time. First, XSL style sheets are XML documents, so we have the XML declaration (<?xml version="1.0"?>). Next, we have the style sheet itself. Notice that all elements have the xsl: prefix, which indicates that they belong to a specific namespace; and they tell the browser that they are instructions, not content to output.
The prefix is actually an alias for the full namespace URL, as determined by your configuration. The namespace is indicated by the xmlns:xsl attribute on the stylesheet element itself. (If you're not sure which to use, go back to "Getting Ready," and follow the steps to check.)
This style sheet contains a single template. We'll discuss selecting data in the next section, but for now note that the match="/" attribute tells the processor to use the document root, or all of the content within the XML file.
The transformation itself is simple: the entire document is output to the page, as indicated by the xsl:value-of element.
Of course, we won't see any of this unless the browser knows to apply this style sheet to the XML document. We can tell the browser what style sheet to use by adding a processing instruction to index.xml:
<?xml version="1.0"?> <?xml-stylesheet href="index.xsl" type="text/xsl"?> <content> <blurb> ...
Now when we use the browser to open index.xml, the processor knows to use the style sheet, as shown in figure 4.
Figure 4 The basic style sheet simply outputs the text.
Because there are no actual HTML tags in the file, the results of this transformation are a jumbled mess, but we'll take care of that next.