Digital Web Magazine

The web professional's online magazine of choice.

An Introduction to Client-Side XSLT: It's Not Just for Server Geeks Anymore

Got something to say?

Share your comments on this topic with other web professionals

In: Articles

By Ken Westin

Published on November 17, 2004

Learning XML by itself is a bit like learning Latin. You memorize the vocabulary and some grammatical rules, but it’s not really useful until you are provided with some context and can actually apply it (in medical school, for example).

We know that XHTML is XML, but it’s not used by most Web designers on a day-to-day basis. Its importance and usefulness aren’t even fully understood by most developers. Unless you’re familiar with a server-side technology where the power of XML has been utilized, you might find XML’s purpose a little ambiguous.

Manipulating XML structure with XSLT

But what about client-side uses of XML? We’re weaning ourselves off old browsers with poor CSS and XHTML support, but there’s another technology worth investigating that has been overlooked in the past few years: XSLT. Support is built into most modern browsers.

XSLT stands for XSL Transformations, and like XML, comes from our friends at the W3C. XSLT and its cousin XSL Formatting Objects (XSL-FO) are used to manipulate the structure of XML and other types of documents (e.g. HTML, PDF and RTF).

The process of transforming a document in XSLT involves converting data from one format or structure to another. Although XSLT is very powerful, the adoption of the language has been slow. It’s been relegated to server-side transformations in some browsers, and there is a perceived steep learning curve.

The good news is that most modern browsers now support XSLT, and although the language requires new thinking about data processing and solving common problems, it’s fairly easy to pick up.

In addition to XSLT, XPath is utilized to assist in the transformation process. Since XPath is such an integral part of XSLT, they are usually considered a single entity. If you are familiar with databases, XPath is to XML as SQL is to a relational database. After all, what good is a data store if there is no way to query it?

Time to learn another language

We have seen the benefits of separating content from design with XHTML and CSS. What if I told you that we haven’t gone far enough?

While the bulk of a design may be stored in CSS files, most documents still contain structural code in addition to content. Moving the majority of the design to CSS definitely improves our design, but it’s not the pure separation-of-content Utopia we’ve been looking for.

Evolution of the Separation of Content and Design

Using XSLT will allow us to completely separate content from design. Instead of mixing structural markup with our data, we split the two. The content exists in XML, the structure of the document in XSL, our design in CSS and the behavior in JavaScript/ECMAScript.

Separation improves workflow

This model not only improves manageability, but also enhances workflow for large-scale Web sites. By allowing programmers and/or database administrators to focus on data and simply generate XML, it relieves them of the need to make UI and usability decisions.

The information architect can then concentrate on creating page structure using XSLT and determining how content should be grouped, sorted and generally displayed.

The designer works with the information architect and uses CSS to apply color schemes, layout, and typography, and JavaScript to add functionality.

As long as the structure does not change, each level can work autonomously. The XML data can be updated without notifying the information architect or designer, the XSLT can change or be replicated for other purposes, and the look and feel can be changed using CSS. This model also goes a long way toward future-proofing, as XSLT can be used to generate almost any document format (e.g. SVG, XForms, XHTML 2.0).

Hitting the books

Since this is an introductory article, I will use a simple example that works in most modern browsers (I recommend using the latest version of Firefox, Internet Explorer or Safari). For our example, we will create a book listing. First, we’ll create the XML file holding nothing but data—book titles and authors.

>> Save this file to your desktop, then open it: books.xml

<?xml version="1.0" encoding="UFT-8" ?>
<books>
<book>
<author>Roth, Philip </author>
<title>American Pastoral</title>
</book>
<book>
<author>Hesse, Hermann</author>
<title>The Glass Bead Game</title>
</book>
...
</book>
</books>

In plain language, the first line simply says: “This is an XML document and I am using version 1.0 with UTF-8 as my encoding.” (You never know—I may have an international book section in the future; see Web Globalization On A Local Budget). Between the <books>...</books> tags we have several <book>...</book> tags, which in turn contain <author>...</author> and <title>...</title> tags. This is a simple XML file that is void of any formatting markup—pure content, essentially.

Now, let’s create our XSLT file.

>> Save this file to your desktop, then open it: books.xsl

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

These lines look a little more menacing than they really are. The second line is known as the root element of the document and is required. Also required is the version and valid namespace of the version you are using. The namespace declaration ("xmlns:xsl=http://www.w3.org/1999/XSL/Transform") is simply a unique identifier to verify that you and the browser or device that is interpreting the XSLT are talking about the same version. It is not critical that you understand namespaces at this point, but you do need to understand that these declarations are required.

Your first transformation

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<head>
<title>My Book Club</title>
</head>
<body>
<h2>Some Good Books </h2>
</body>
</html>
</xsl:template>

</xsl:stylesheet>

The HTML should look familiar to you. The only thing new here is the set of tags wrapped around the HTML content. One of the more powerful aspects of XSLT is the template concept: “Hey, XSL processor! If you find a root node, output this content in the format I have specified."

So, how do we get our content (books.xml) and our structure (books.xsl) together? To keep things simple, we are just going to utilize the XSLT processor native to the browser.

>> Add the line in bold type here to books.xml:

<?xml version="1.0" encoding="utf-8" ?>
<?xml-stylesheet type="text/xsl" href="books.xsl"?>
<books>
<book>
<author>Roth, Philip </author>
<title>American Pastoral</title>
</book>
<book>
<author>Hesse, Hermann</author>
<title>The Glass Bead Game</title>
</book>
...
</books>

This line will tell the browser what XSLT file to use in the transformation. Save books.xml and open it up in your browser. You should see:

Some Good Books

If you see the line above, congratulations! You just implemented your first transformation. This means that the XSL found the element (tag) and rendered the HTML as it was supposed to.

Outputting data

Now, let’s actually output the data from the file. To do this, we need to add some instructions to our XSL.

>> Add the lines in bold type here to books.xml:

<xsl:template match="/">
<html>
<head>
<title>Some Good Books </title>
</head>
<body>
<h2>Some Good Books </h2>
<xsl:apply-templates />
</body>
</html>
</xsl:template>

<xsl:template match="books">
<ul id="booklist">
<xsl:apply-templates / >
</ul>

</xsl:template>


<xsl:template match="book">
<li><em><xsl:value-of select="title" /></em> by <xsl:value-of select="author" /></li>
</xsl:template>

You should recognize some of the markup in this example as simple HTML. All we are doing here is creating an unordered list of books from the XML file.

One of the most powerful aspects of XSLT is its use of templates that “match” a set of conditions you define. So, in the first template we matched the root node, and when the processor found it, added the HTML content defined. Just below <h2>Some Good Books</h2>, you will see a new tag: <xsl:apply-templates />. Think of this as a dynamic include that’s grabbing the next template (which, in our case, is this <xsl:template match="books">). If the <books> node is found, the <ul>; and its matching tag are created. The <xsl:apply-templates />; tag repeats, which tells the processor to move on to the next template that matches the <book> element.

Here is where we will actually be outputting content from our XML file. Inside the <xsl:template match="book"> tags you will see <xsl:value-of select="title" />. This is telling the processor to get the text that is between the <title> tags in our books.xml file and output the content in the transformation. Then another tag outputs the author’s name: <xsl:value-of select ="author" />. We close the template and since there are no additional templates to process, the transformation is complete and the processor spits out the result tree.

Sordid Sort

The data is output in the same order it appears in the XML file. However, what if our book list consisted of 100 books and we wanted to sort them alphabetically by the author’s last name? And what about pagination? All we have to do is add a short tag.

>> Add the line in bold type here to books.xsl:

<xsl:template match="books">
<ul>
<xsl:apply-templates>
<xsl:sort select="author" />
</xsl:apply-templates>
</ul>
</xsl:template>

Pretty it up

With some additional markup and an attached stylesheet, the final product could look like this.

This tutorial only scratches the surface of what can be accomplished with XSLT. There are many advanced methods and techniques, but some are only supported by one browser or are implemented differently (sound familiar?), such as using JavaScript to do transformations. Linking a stylesheet in your XML file works in most browsers, so it’s a good way to start learning XSLT.

If you need to support older browsers, you can use these files to do the transformation using a server-side language such as ASP.NET, ColdFusion MX, JSP and PHP.

Got something to say?

Share your comments  with other professionals (36 comments)

Related Topics: XML, Programming, Basics

 

Ken Westin is based in Portland, Oregon and is currently the Founder and CEO of GadgetTrak, the provider of mobile security and theft recovery solutions.

Media Temple

via Ad Packs