How does XSLT transform XML | WebReference

How does XSLT transform XML

Back Contents Next

How does XSLT transform XML?



q        The first stage is a structural transformation, inÂ which the data is converted from the structure of the incoming XML document to a structure that reflects the desired output.

q        The second stage is formatting, inÂ which the new structure is output in the required format such as HTML or PDF.




A white paper describing Motorola's VOXML Voice Markup Language can be found at

Let's now delve into the first stage, transformation - the stage with which



So how does this come about? Before the advent of XSLT, you could only process incoming XML documents by writing a custom application. The application wouldn't actually need to parse the raw XML, but it would need to invoke an XML parser, via a defined Application Programing Interface (API),Â to get information from the document and do something with it. There are two principal APIs for achieving this: the Simple API for XML (SAX) and the Document Object Model (DOM).








XSLT still relies on a parser Â– Â be it a DOM parser or a SAX-compliant one Â– to convert the XML document in to a "tree structure". It is the structure of this tree representation of the document that XSLT manipulates, not the document itself. If you are familiar with the DOM, then you will be happy with the idea of treating every item in an XML document (elements, attributes, processing instructions etc.) as a node. With XSLT we have a high-level language that can navigate around a node tree, select specific nodes and perform complex manipulations on these nodes.



The description of XSLT given thus far (a declarative language that can navigate to and select specific data and then manipulate that data) may strike you as being similar to that of the standard database query language: SQL. Let's take a closer look at this comparison.

XSLT and SQL: an Analogy

I like to think of an analogyÂ with relational databases. In a relational database, the data consists of a set of tables. By themselves, the tables are not much use, the data might as well be stored in flat files in comma-separated values format. The power of a relational database doesn't come from its data structure; it comes from the language that processes the data, SQL. In the same way, XML on its own just defines a data structure. It's a bit richer than the tables of the relational model, but by itself it doesn't actually do anything very useful. It's when we get a high-level language expressly designed to manipulate the data structure that we start to find we've got something interesting on our hands: and for XML data that language is XSLT.


Superficially, SQL and XSLT are very different languages. But if you look below the surface, they actually have a lot in common. For starters: in order to process specific data, be it in a relational database or an XML document, the processing language must incorporate a declarative query syntax for selecting the data that needs to be processed. In SQL, that's the SELECT statement. In XSLT, the equivalent is the XPath expression.


The XPath expression language forms an essential part of XSLT, though it is actually defined in a separate W3C Recommendation ( becauseÂ it can also be used independently of XSLT (the relationship between XPath and XSLT is discussed further on page 23).


The XPath query syntax is designed to retrieve nodes from an XML document, based on a path through the XML document or the context in which the node appears. It allows access to specific nodes, while preserving the hierarchy and structure of the document. XSLT is then used to manipulate the results of these "queries" (rearranging selected nodes, constructing new nodes etc).


There are further similarities between XSLT and SQL:


q        Both languages augment the basic queryÂ facilities with useful additions for performing basic arithmetic, string manipulation, and comparison operations.

q        Both languages supplementÂ the declarative query syntax with semi-procedural facilities for describing the sequence of processing to be carried out, and they also provide hooks to escape into conventional programming languages where the algorithms start to get too complex.

q        Both languages have an important property called closure, which means that the output has the same data structure as the input. For SQL15, this structure is tables, for XSLT it is trees Â– the tree representation of XML documents. The closure property is extremely valuable because it means operations performed using the language can be combined end-to-end to define bigger more complex operations: you just take the output of one operation and make it the input of the next operation. In SQL you can do this by defining views or subqueries; in XSLT you can do it by passing your data through a series of stylesheets.


In the real world, of course, XSLT and SQL have to coexist. There are many possible relationships, but typically data will be stored in relational databases and transmitted between systems in XML. The two languages don't fit together as comfortably as one would like, because the data models are so different. But XSLT transformations can play an important role in bridging the divide. A number of database vendors are working on products that integrate XML and SQL, though there are no standards in this area as yet.


SQL Server 2000 will support XPath queries on its data. Prior to the release of SQL Server 2000, Microsoft has released the XML SQL Technology Preview, which allows access to data in a SQL Server 6.5 or 7.0 databases in XML form.

The XML SQL Technology Preview is available from


Before we move on to look at a simple working example of an XSLT transformation, we need to briefly discuss a few of the XSLT processors that are available to effect these transformations.


XSLT Processors

The principle role of an XSLT processor is toÂ apply an XSLT stylesheet to an XML source document and produce a result document. It is important to note that each of these is an application of XML and so the underlying structure of each is a tree. So, in fact, the XSLT processor handles three trees.


There are several XSLT processors to choose from. Here I'll mention three: Saxon,Â xt, and Microsoft MSXML3. All of these can be downloaded free of charge (but do read the licensing conditions).


These three processors and several others are described in Chapter 10.

Saxon is an open source XSLT processor developed by the author of this book. It is a Java application, and can be runÂ directly from the command prompt: no web server or browser is required. The Saxon program will transform the XML document to, say, a HTML document, which can then be placed on a web server. In this example, both the browser and web server only deal with the transformed document.


If you are running Windows (95/98/NT/2000) the simplest way to use it is to download Instant Saxon, which is packaged as a Windows executable. You will need to have Java installed, but that will be there already if you have any recent version of Internet Explorer. On non-Windows platforms you will need to install the full Saxon product and follow the instructions that come with it. You can download Instant Saxon for free from Saxon will run with any XML parser that implements the SAX interface (in its original Java form).


xt is another openÂ source XSLT processor developed by James Clark, the editor of the XSLT specification. Like Saxon, this is a Java application that can be run from the command prompt; it too has a simple packaged version for the Windows platform and a full version for other environments. This time the download is from Like Saxon, xt can operate with any SAX-compliant parser.


Alternatively, you can run XSLT stylesheets actually within Internet Explorer. You'll need to install Internet Explorer 5 and the latest version of the Microsoft MSXML processor, which you can find at The information here is correct for the 15 March 2000 technology preview, referred to as MSXML3, but Microsoft has promised a rapid sequence of new releases, so check the latest position. MSXML3 comes with a new version of the MSXML parser.


Download and install both the SDK and the run-time package. Installing the SDK creates a program called xmlinst.exe, typically in the windows\system directory. Run this program to establish MSXML3 as the default XML processor to be used by Internet Explorer (if you don't do this, IE5 will try to use the old 1998 MSXML processor, which implements an obsolete dialect of XSL that is quite different from the language described in this book: see Chapter 10 for details). The big advantage of Microsoft's technology is that the XSLT processing can take place on the browser.


I've avoided talking about specific products in most of the book, because the information is likely to change quite rapidly. It's best to get the latest status from the web. Some good places to start are:






An Example Stylesheet

Now we're ready to take a look at an example of using XSLT to transform a very simple XML document.


Example: A "Hello, world!" XSLT Stylesheet


Kernighan and Ritchie in their classic The C Programming Language originated the idea of presenting a trivial but complete program right at the beginning of the book, and ever since then the "Hello world" program has been an honored tradition. Of course, a complete description of how this example works is not possible until all the concepts have been defined: so if you feel I'm not explaining it fully, don't worry Â– the explanations will come later.



What kind of transformation would we like to do? Let's try transforming the following XML document:



<greeting>Hello, world!</greeting>


A simple node-tree-representation of this document would look as follows:



There is one root node per document. The root node in the XSLT model performs the same function as the document node in the DOM model. The XML declaration is not visible to the parser and, therefore, is not included in the tree.



Our required output is theÂ following HTML, which will simply change the browser title to "Today's Greeting" and display whatever greeting is in the source XML file:

















Â Â  <title>Today's greeting</title>



Â Â  <p>Hello, world!</p>




XSLT StyleSheet

Without any more ado, here's the XSLT stylesheet to effect the transformation:




Â Â  version="1.0"

Â Â  xmlns:xsl="">


<xsl:template match="/">

Â Â  <html>

Â Â  <head>

Â Â Â Â Â  <title>Today's greeting</title>

Â Â  </head>

Â Â  <body>

Â Â  Â Â Â <p><xsl:value-of select="greeting"/></p>

Â Â  </body>

Â Â  </html>





Running the Stylesheet

You can run this stylesheet using any of the three processors described in the previous section.


With Saxon, theÂ steps are:


q        Download the processor

q        Install the executable saxon.exe in a suitable directory, and make this the current directory











q        Using Notepad, type the two files above into hello.xml and hello.xsl respectively, within this directory (or get them from the Wrox web site at

q        Bring up an MSDOS-style console window (Start | Programs | MSDOS Prompt)

q        Type the following at the command prompt:
saxon hello.xml hello.xsl

q        Admire the HTML displayed on the standard output


If you want to view the output using your browser, simply save the command line output as an HTML file, in the following manner:


Saxon hello.xml hello.xsl > hello.html


The procedure is very similar if you use xt. This time the command to use the Windows executable is xt rather than saxon. It should give the same result.



Finally, you can run the stylesheet actually within Internet Explorer. You need to modify the XML source file to include a reference to the stylesheet, so it now reads:




<greeting>Hello, world!</greeting>


Now you should simply be able to double-click on the hello.xml file, which will bring up IE5 and load hello.xml into the browser. IE5 reads the XML file, discovers what stylesheet is needed, loads the stylesheet, executes it to perform the transformation, and displays the resulting HTML. If you don't see the text "Hello, world!" on the screen, but just the XML file, this is because you're using the original XSL interpreter that Microsoft issued with IE5, not the MSXML3 version. If you see the stylesheet displayed, this also indicates that you haven't completed the installation process correctly: remember to run the xmlinst.exe program.


How it Works

If you've succeeded in running this example, or even if you just want to get on with reading the book, you'll want to know how it works. Let's dissect it:














This is just the standard XML heading. The interesting point is that an XSLT stylesheet is itself an XML document. I'll have more to say about this later in the chapter. I've used iso-8859-1 character encoding (which is the official name for the character set that Microsoft calls "ANSI") because in Western Europe and North America it's the character set that most text editors support. If you've got a text editor that supports UTF-8 or some other character encoding, feel free to use that instead.



Â Â  xmlns:xsl=""

Â Â  version="1.0">


This is the standard XSLT heading. In XML terms it's an element start tag, and it identifies the document as a stylesheet. The xmlns:xsl attribute is an XML Namespace declaration, which indicates that the prefix xsl is going to be used for elements defined in the W3C XSLT specification: XSLT makes extensive use of XML namespaces, and all the element names defined in the standard are prefixed with this namespace, to avoid any clash with names used in your source document. The version attribute indicates that the stylesheet is only using features from version 1.0 of the XSLT standard, which at the moment is the only version there is.


Let's move on:


<xsl:template match="/">


An <xsl:template> element defines a template rule to be triggered when a particular part of the source document is being processed. The attribute match="/" indicates that this particular rule is triggered right at the start of processing the source document. Here Â«/Â» is an XPath expression which identifies the root node of the document: an XML document has a hierarchic structure, and in the same way as UNIX uses the special filename Â«/Â» to indicate the root of a hierarchic filestore, XPath uses Â«/Â» to represent the root of the XML content hierarchy. The DOM model calls this the Document object, but in XPath it is called the root.




Â Â  <title>Today's greeting</title>















Once this rule is triggered, the body of the template says what output to generate. Most of the template body here is a sequence of HTML elements and text to be copied into the output file. There's one exception: an <xsl:value-of> element, which we recognize as an XSL instruction because it uses the namespace prefix xsl. This particular instruction copies the value of a node in the source document to the output document. . The SELECT attribute of the element specifies the node for which the value should be evaluated. The XPath expression Â«greeting>> means: "find the set of all <greeting> elements that are children of the node that this template rule is currently processing". In this case, this means the <greeting> element that's the outermost element of the source document. The <xsl:value-of> instruction then extracts the text node of this element, and copies it to the output at the relevant place, in other words within the generated <p> element.


All that remains is to finish what we started:







In fact, for a simple stylesheet like the one shown above, you can cut out some of the red tape. Since there is only one template rule, the <xsl:template> element can actually be omitted. The following is a complete, valid stylesheet equivalent to the preceding one:


<html xsl:version="1.0"

Â Â Â Â Â  xmlns:xsl="">


Â Â  <title>Today's greeting</title>







This simplified syntax is designed to make XSLT look familiar to people who have learnt to use proprietary template languages which allow you to write a skeleton HTML page with special tags (analogous to <xsl:value-of>) to insert variable data at the appropriate place. But as we'll see, XSLT is much more powerful than that.


Why would you want to place today's greeting in a separate XML file and display it using a stylesheet? One reason is that you might want to show the greeting in different ways depending on the context; for example, it might be shown differently on a different device. In this case you could write a different stylesheet to transform the same source document in a different way. This raises the question of how a stylesheet gets selected at run-time. There is no single answer to this question. As we saw above, Saxon and xt have interfaces that allow you to nominate both the stylesheet and the source document to use. The same thing can also be achieved with the Microsoft XSLT product, though it requires some scripting on the HTML page: the <?xml-stylesheet?> processing instruction which I used in the example above only works if you want to use the same stylesheet every time.


It's time now to take a closer look at the relationship between XSLT and XPath and other XML-related technologies.

©1999 Wrox Press Limited, US and UK.

Produced by Michael Claßen
All Rights Reserved. Legal Notices.

Created: Jan. 05, 2001
Revised: Jan. 05, 2001