XSL simplifies design changes

Talking Shop

In my last column, I mentioned that a fundamental feature of XML is its ability to store data independently of its presentation. This column will elaborate on that concept, with instructions on how to display an XML document using XSL.

XSL stands for Extensible Stylesheet Language, and is used to create layout templates that specify how the data in XML documents should be formatted for display.

In cases where a Web site has multiple pages with the same layout but different content, the advantages of using XML/XSL over HTML become very clear. Using traditional static HTML pages, the design elements are repeated in code for every page. Changing the look of the site means going through every page of content and altering the HTML. XSL allows you to code your layout in one file, creating a template that can be applied to any number of XML documents (pages of data). Any change of design can then be made by altering the one XSL file, and would propagate throughout the site.

An XSL template itself is actually an XML document, and must be well-formed according to the same conventions (all opened tags must be closed, tags must be properly nested, etc). An XSL document starts with the following declaration:

Let’s create an example XSL template to format a catalogue of books stored as XML. Assume that the XML document starts with a top-level “catalogue” element, and contains a number of “book” elements, each with “title,” “author,” and “publisher” sub-elements.

Note: You may need to upgrade your browser to Internet Explorer 6 in order to properly view the example.

After beginning with the above stylesheet declaration, the next step is to open an XSL template element that specifies what branch of the XML document to apply the formatting to. To specify the whole document, the tag looks like this:

We’ll want to apply our template to the “catalogue” branch, so we should change the match attribute to look like this:

Suppose we wanted to display our list of books in a table. Each book would appear in a table row, with “title,” “author” and “publisher” as columns. We’ll need our XSL template to loop through all of the “book” elements in the catalogue, printing each along with the HTML tags for creating the table. XSL provides a “for-each” tag to execute this type of looping. And “value-of” tags are used to insert data from the XML document. Notice that that because the “value-of” tags exist as standalone elements with nothing nested between them, they are closed simply by adding the space and slash at the end of the opening tag. The complete template looks like this:


Finally, link the template to the data by adding this line to your XML documents:

Open the XML document in IE6 to view the results.

Cooney works as a programmer/analyst for a major Canadian book publisher. He can be reached at robert_cooney@hotmail.com.