- The Basic Idea
- The Mechanics of XML-to-HTML Transformation
- The Project
- What You Need to Know
- Tools Needed for XSL Transformation
- Summary
The Mechanics of XML-to-HTML Transformation
The purpose of an XSLT style sheet is to take an XML document and transform it into some other form in some predictable way. This is done by using <i>templates</i>, which can single out specific <i>Node</i>s or other information and then use them (usually) to create a new document.
XSLT style sheets will be covered in detail in Article 2, but let's look at a brief example. Suppose that we had an XML document listing names and phone numbers, and we wanted to display them on a Web page as a bulleted list, with the phone numbers in parentheses.
We might have an XML file like the following:
<?xml version="1.0"?> <personnel> <employee> <fullname>Karen Smith</fullname> <phone>352-555-1234</phone> </employee> <employee> <fullname>John Drew</fullname> <phone>329-555-8827</phone> </employee> <employee> <fullname>Frank McCartney</fullname> <phone>983-555-8273</phone> </employee> </personnel>
To create a bulleted list, we might create this style sheet:
<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <html> <head><title>Phone List</title></head> <body> <h1>Employee List</h1> <ul> <xsl:apply-templates/> </ul> </body> </html> </xsl:template> <xsl:template match="employee"> <li> <xsl:value-of select="fullname"/> (<xsl:value-of select="phone"/>) </li> </xsl:template> </xsl:stylesheet>
Processing these files gives us HTML of the following, as shown in Figure 1:
<html> <head> <title>Phone List</title></head> <body> <h1>Employee List</h1> <ul> <li>Karen Smith (352-555-1234)</li> <li>John Drew (329-555-8827)</li> <li>Frank McCartney (983-555-8273)</li> </ul> </body> </html>
Making even a small change to the style sheet affects the eventual page. For example, change the unordered list (<ul>) to an ordered list (<ol>), and the employees are numbered on the page, as shown in Figure 2:
... <xsl:template match="/"> <html> <head><title>Phone List</title></head> <body> <h1>Employee List</h1> <ol> <xsl:apply-templates/> </ol> </body> </html> </xsl:template> ...
This personalization project will show you how to allow the user to choose a preferred style sheet, which you then dynamically use to create their pages. You can take this concept as far as you like. Not only can users choose a style sheet, but they can also give you information that allows you to create a custom style sheet for them.
The information you take can be simple (such as a color or font that is added to a section of the style sheet listing CSS properties), or more complex. A later article will show you how to allow users to choose what content they want and where they want it on the page. You can then take this information and use it to dynamically create an entire XSL style sheet, element by XML element.