You are on page 1of 49

XSL Languages

It started with XSL and ended up with XSLT, XPath, and XSL­FO.

It Started with XSL

XSL stands for EXtensible Stylesheet Language.

The World Wide Web Consortium (W3C) started to develop XSL because there was a need for an XML­
based Stylesheet Language. 

CSS = HTML Style Sheets

HTML uses predefined tags and the meaning of the tags are well understood.

The <table> element in HTML defines a table ­ and a browser knows how to display it.

Adding styles to HTML elements is simple. Telling a browser to display an element in a special font or 
color, is easy with CSS. 

XSL = XML Style Sheets

XML does not use predefined tags (we can use any tag­names we like), and the meaning of these tags are 
not well understood.

A <table> element could mean an HTML table, a piece of furniture, or something else ­ and a browser does 
not know how to display it.

XSL describes how the XML document should be displayed!

XSL ­ More Than a Style Sheet Language

XSL consists of three parts:

• XSLT ­ a language for transforming XML documents
• XPath ­ a language for navigating in XML documents
• XSL­FO ­ a language for formatting XML documents

Introduction to XSLT

XSLT is a language for transforming XML documents into XHTML documents or to other XML 
documents.

XPath is a language for navigating in XML documents.

What You Should Already Know

Before you continue you should have a basic understanding of the following:
• HTML / XHTML
• XML / XML Namespaces
• XPath

What is XSLT?

• XSLT stands for XSL Transformations
• XSLT is the most important part of XSL
• XSLT transforms an XML document into another XML document
• XSLT uses XPath to navigate in XML documents
• XSLT is a W3C Recommendation

XSLT = XSL Transformations

XSLT is the most important part of XSL.

XSLT is used to transform an XML document into another XML document, or another type of document 
that is recognized by a browser, like HTML and XHTML. Normally XSLT does this by transforming each 
XML element into an (X)HTML element.

With XSLT you can add/remove elements and attributes to or from the output file. You can also rearrange 
and sort elements, perform tests and make decisions about which elements to hide and display, and a lot 
more.

A common way to describe the transformation process is to say that XSLT transforms an XML source­
tree into an XML result­tree.

XSLT Uses XPath

XSLT uses XPath to find information in an XML document. XPath is used to navigate through elements 
and attributes in XML documents.

How Does it Work?

In the transformation process, XSLT uses XPath to define parts of the source document that should match 
one or more predefined templates. When a match is found, XSLT will transform the matching part of the 
source document into the result document.

XSLT Browsers

Nearly all major browsers have support for XML and XSLT.

Mozilla Firefox

As of version 1.0.2, Firefox has support for XML and XSLT (and CSS).

Mozilla
Mozilla includes Expat for XML parsing and has support to display XML + CSS. Mozilla also has some 
support for Namespaces.

Mozilla is available with an XSLT implementation.

Netscape

As of version 8, Netscape uses the Mozilla engine, and therefore it has the same XML / XSLT support as 
Mozilla.

Opera

As of version 9, Opera has support for XML and XSLT (and CSS). Version 8 supports only XML + CSS.

Internet Explorer

As of version 6, Internet Explorer supports XML, Namespaces, CSS, XSLT, and XPath.

Version 5 is NOT compatible with the official W3C XSL Recommendation.

XSLT ­ Transformation

xample study: How to transform XML into XHTML using XSLT.
The details of this example will be explained in the next chapter. 
Correct Style Sheet Declaration
The root element that declares the document to be an XSL style sheet is <xsl:stylesheet> or 
<xsl:transform>.
Note: <xsl:stylesheet> and <xsl:transform> are completely synonymous and either can be used!
The correct way to declare an XSL style sheet according to the W3C XSLT Recommendation is:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

or:

<xsl:transform version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

To get access to the XSLT elements, attributes and features we must declare the XSLT namespace at the 
top of the document.

The xmlns:xsl="http://www.w3.org/1999/XSL/Transform" points to the official W3C XSLT namespace. If 
you use this namespace, you must also include the attribute version="1.0".

Start with a Raw XML Document

We want to transform the following XML document ("cdcatalog.xml") into XHTML:
<?xml version="1.0" encoding="ISO­8859­1"?>
<catalog>
  <cd>
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>10.90</price>
    <year>1985</year>
  </cd>
.
.
.
</catalog>

Viewing XML Files in Firefox and Internet Explorer: Open the XML file (typically by clicking on a 
link) ­ The XML document will be displayed with color­coded root and child elements. A plus (+) or minus 
sign (­) to the left of the elements can be clicked to expand or collapse the element structure. To view the 
raw XML source (without the + and ­ signs), select "View Page Source" or "View Source" from the 
browser menu.

Viewing XML Files in Netscape 6: Open the XML file, then right­click in XML file and select "View 
Page Source". The XML document will then be displayed with color­coded root and child elements.

Viewing XML Files in Opera 7: Open the XML file, then right­click in XML file and select "Frame" / 
"View Source". The XML document will be displayed as plain text.

Create an XSL Style Sheet

Then you create an XSL Style Sheet ("cdcatalog.xsl") with a transformation template: 

<?xml version="1.0" encoding="ISO­8859­1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <html>
  <body>
    <h2>My CD Collection</h2>
    <table border="1">
    <tr bgcolor="#9acd32">
      <th align="left">Title</th>
      <th align="left">Artist</th>
    </tr>
    <xsl:for­each select="catalog/cd">
    <tr>
      <td><xsl:value­of select="title"/></td>
      <td><xsl:value­of select="artist"/></td>
    </tr>
    </xsl:for­each>
    </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

Link the XSL Style Sheet to the XML Document

Add the XSL style sheet reference to your XML document ("cdcatalog.xml"):

<?xml version="1.0" encoding="ISO­8859­1"?>
<?xml­stylesheet type="text/xsl" href="cdcatalog.xsl"?>
<catalog>
  <cd>
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>10.90</price>
    <year>1985</year>
  </cd>
.
.
.
</catalog>

If you have an XSLT compliant browser it will nicely transform your XML into XHTML.

XSLT <xsl:template> Element

An XSL style sheet consists of one or more set of rules that are called templates.

A template contains rules to apply when a specified node is matched.

The <xsl:template> Element

The <xsl:template> element is used to build templates.

The match attribute is used to associate a template with an XML element. The match attribute can also be 
used to define a template for the entire XML document. The value of the match attribute is an XPath 
expression (i.e. match="/" defines the whole document).

Ok, let's look at a simplified version of the XSL file from the previous chapter:

<?xml version="1.0" encoding="ISO­8859­1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
 <html>
 <body>
   <h2>My CD Collection</h2>
   <table border="1">
     <tr bgcolor="#9acd32">
       <th>Title</th>
       <th>Artist</th>
     </tr>
     <tr>
       <td>.</td>
       <td>.</td>
     </tr>
   </table>
 </body>
 </html>
</xsl:template>
</xsl:stylesheet>

Since an XSL style sheet is an XML document itself, it always begins with the XML declaration: <?xml 
version="1.0" encoding="ISO­8859­1"?>.

The next element, <xsl:stylesheet>, defines that this document is an XSLT style sheet document (along 
with the version number and XSLT namespace attributes).

The <xsl:template> element defines a template. The match="/" attribute associates the template with the 
root of the XML source document.

The content inside the <xsl:template> element defines some HTML to write to the output.

The last two lines define the end of the template and the end of the style sheet.

The result of the transformation above will look like this:

My CD Collection

Title Artist
. .

The result from this example was a little disappointing, because no data was copied from the XML 
document to the output.

In the next chapter you will learn how to use the <xsl:value­of> element to select values from the XML 
elements.

XSLT <xsl:value­of> Element

The <xsl:value­of> element is used to extract the value of a selected node.

The <xsl:value­of> Element
The <xsl:value­of> element can be used to extract the value of an XML element and add it to the output 
stream of the transformation:

<?xml version="1.0" encoding="ISO­8859­1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
 <html>
 <body>
   <h2>My CD Collection</h2>
   <table border="1">
     <tr bgcolor="#9acd32">
       <th>Title</th>
       <th>Artist</th>
     </tr>
     <tr>
      <td><xsl:value­of select="catalog/cd/title"/></td>
      <td><xsl:value­of select="catalog/cd/artist"/></td>
     </tr>
   </table>
 </body>
 </html>
</xsl:template>
</xsl:stylesheet>

Note: The value of the select attribute is an XPath expression. An XPath expression works like navigating a 
file system; where a forward slash (/) selects subdirectories.

The result of the transformation above will look like this:

My CD Collection

Title Artist
Empire Burlesque Bob Dylan

The result from this example was also a little disappointing, because only one line of data was copied from 
the XML document to the output.

In the next chapter you will learn how to use the <xsl:for­each> element to loop through the XML 
elements, and display all of the records.

XSLT <xsl:for­each> Element

The <xsl:for­each> element allows you to do looping in XSLT.

The <xsl:for­each> Element

The XSL <xsl:for­each> element can be used to select every XML element of a specified node­set:

<?xml version="1.0" encoding="ISO­8859­1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <html>
  <body>
    <h2>My CD Collection</h2>
    <table border="1">
      <tr bgcolor="#9acd32">
        <th>Title</th>
        <th>Artist</th>
      </tr>
      <xsl:for­each select="catalog/cd">
      <tr>
        <td><xsl:value­of select="title"/></td>
        <td><xsl:value­of select="artist"/></td>
      </tr>
      </xsl:for­each>
    </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

Note: The value of the select attribute is an XPath expression. An XPath expression works like navigating a 
file system; where a forward slash (/) selects subdirectories.

The result of the transformation above will look like this:

My CD Collection

Title Artist
Empire Burlesque Bob Dylan
Hide your heart Bonnie Tyler
Greatest Hits Dolly Parton
Still got the blues Gary More
Eros Eros Ramazzotti
One night only Bee Gees
Sylvias Mother Dr.Hook
Maggie May Rod Stewart
Romanza Andrea Bocelli
When a man loves a woman Percy Sledge
Black angel Savage Rose
1999 Grammy Nominees Many
For the good times Kenny Rogers
Big Willie style Will Smith
Tupelo Honey Van Morrison
Soulsville Jorn Hoel
The very best of Cat Stevens
Stop Sam Brown
Bridge of Spies T`Pau
Private Dancer Tina Turner
Midt om natten Kim Larsen
Pavarotti Gala Concert Luciano Pavarotti
The dock of the bay Otis Redding
Picture book Simply Red
Red The Communards
Unchain my heart Joe Cocker
Filtering the Output
We can also filter the output from the XML file by adding a criterion to the select attribute in the <xsl:for­
each> element.
<xsl:for­each select="catalog/cd[artist='Bob Dylan']">
Legal filter operators are:
• =  (equal)
• != (not equal)
• &lt; less than
• &gt; greater than
Take a look at the adjusted XSL style sheet:
<?xml version="1.0" encoding="ISO­8859­1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
 <html>
  <body>
  <h2>My CD Collection</h2>
  <table border="1">
   <tr bgcolor="#9acd32">
      <th>Title</th>
      <th>Artist</th>
   </tr>
   <xsl:for­each select="catalog/cd[artist='Bob Dylan']">
   <tr>
      <td><xsl:value­of select="title"/></td>
      <td><xsl:value­of select="artist"/></td>
   </tr>
   </xsl:for­each>
  </table>
 </body>
 </html>
</xsl:template>
</xsl:stylesheet>

The result of the transformation above will look like this:
My CD Collection

Title Artist
Empire Burlesque Bob Dylan

XSLT <xsl:sort> Element

The <xsl:sort> element is used to sort the output.

Where to put the Sort Information

To sort the output, simply add an <xsl:sort> element inside the <xsl:for­each> element in the XSL file:

<?xml version="1.0" encoding="ISO­8859­1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <html>
  <body>
    <h2>My CD Collection</h2>
    <table border="1">
      <tr bgcolor="#9acd32">
        <th>Title</th>
        <th>Artist</th>
      </tr>
      <xsl:for­each select="catalog/cd">
      <xsl:sort select="artist"/>
      <tr>
        <td><xsl:value­of select="title"/></td>
        <td><xsl:value­of select="artist"/></td>
      </tr>
      </xsl:for­each>
    </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

Note: The select attribute indicates what XML element to sort on.

The result of the transformation above will look like this:

My CD Collection

Title Artist
Romanza Andrea Bocelli
One night only Bee Gees
Empire Burlesque Bob Dylan
Hide your heart Bonnie Tyler
The very best of Cat Stevens
Greatest Hits Dolly Parton
Sylvias Mother Dr.Hook
Eros Eros Ramazzotti
Still got the blues Gary Moore
Unchain my heart Joe Cocker
Soulsville Jorn Hoel
For the good times Kenny Rogers
Midt om natten Kim Larsen
Pavarotti Gala Concert Luciano Pavarotti
1999 Grammy Nominees Many
The dock of the bay Otis Redding
When a man loves a woman Percy Sledge
Maggie May Rod Stewart
Stop Sam Brown
Black angel Savage Rose
Picture book Simply Red
Bridge of Spies T`Pau
Red The Communards
Private Dancer Tina Turner
Tupelo Honey Van Morrison
Big Willie style Will Smith

XSLT <xsl:if> Element

The <xsl:if> element is used to put a conditional test against the content of the XML file.

The <xsl:if> Element

To put a conditional if test against the content of the XML file, add an <xsl:if> element to the XSL 
document.

Syntax
<xsl:if test="expression">
  ...
  ...some output if the expression is true...
  ...
</xsl:if>

Where to Put the <xsl:if> Element

To add a conditional test, add the <xsl:if> element inside the <xsl:for­each> element in the XSL file:
<?xml version="1.0" encoding="ISO­8859­1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <html>
  <body>
    <h2>My CD Collection</h2>
    <table border="1">
      <tr bgcolor="#9acd32">
        <th>Title</th>
        <th>Artist</th>
      </tr>
      <xsl:for­each select="catalog/cd">
      <xsl:if test="price &gt; 10">
        <tr>
          <td><xsl:value­of select="title"/></td>
          <td><xsl:value­of select="artist"/></td>
        </tr>
      </xsl:if>
      </xsl:for­each>
    </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

Note: The value of the required test attribute contains the expression to be evaluated.

The code above will only output the title and artist elements of the CDs that has a price that is higher than 
10.

The result of the transformation above will look like this:

My CD Collection

Title Artist
Empire Burlesque Bob Dylan
Still got the blues Gary Moore
One night only Bee Gees
Romanza Andrea Bocelli
Black Angel Savage Rose
1999 Grammy Nominees Many

XSLT <xsl:choose> Element

The <xsl:choose> element is used in conjunction with <xsl:when> and <xsl:otherwise> to express multiple 
conditional tests.

The <xsl:choose> Element
Syntax
<xsl:choose>
  <xsl:when test="expression">
    ... some output ...
  </xsl:when>
  <xsl:otherwise>
    ... some output ....
  </xsl:otherwise>
</xsl:choose>

Where to put the Choose Condition

To insert a multiple conditional test against the XML file, add the <xsl:choose>, <xsl:when>, and 
<xsl:otherwise> elements to the XSL file:

<?xml version="1.0" encoding="ISO­8859­1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <html>
  <body>
    <h2>My CD Collection</h2>
    <table border="1">
      <tr bgcolor="#9acd32">
        <th>Title</th>
        <th>Artist</th>
      </tr>
      <xsl:for­each select="catalog/cd">
      <tr>
        <td><xsl:value­of select="title"/></td>
       <xsl:choose>
          <xsl:when test="price &gt; 10">
            <td bgcolor="#ff00ff">
            <xsl:value­of select="artist"/></td>
          </xsl:when>
          <xsl:otherwise>
            <td><xsl:value­of select="artist"/></td>
          </xsl:otherwise>
        </xsl:choose>
      </tr>
      </xsl:for­each>
    </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>
The code above will add a pink background­color to the "Artist" column WHEN the price of the CD is 
higher than 10.

The result of the transformation will look like this:

My CD Collection

Title Artist
Empire Burlesque Bob Dylan
Hide your heart Bonnie Tyler
Greatest Hits Dolly Parton
Still got the blues Gary Moore
Eros Eros Ramazzotti
One night only Bee Gees
Sylvias Mother Dr.Hook
Maggie May Rod Stewart
Romanza Andrea Bocelli
When a man loves a woman Percy Sledge
Black angel Savage Rose
1999 Grammy Nominees Many
For the good times Kenny Rogers
Big Willie style Will Smith
Tupelo Honey Van Morrison
Soulsville Jorn Hoel
The very best of Cat Stevens
Stop Sam Brown
Bridge of Spies T`Pau
Private Dancer Tina Turner
Midt om natten Kim Larsen
Pavarotti Gala Concert Luciano Pavarotti
The dock of the bay Otis Redding
Picture book Simply Red
Red The Communards
Unchain my heart Joe Cocker

Another Example

Here is another example that contains two <xsl:when> elements:

<?xml version="1.0" encoding="ISO­8859­1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <html>
  <body>
    <h2>My CD Collection</h2>
    <table border="1">
      <tr bgcolor="#9acd32">
        <th>Title</th>
        <th>Artist</th>
      </tr>
      <xsl:for­each select="catalog/cd">
      <tr>
        <td><xsl:value­of select="title"/></td>
       <xsl:choose>
          <xsl:when test="price &gt; 10">
            <td bgcolor="#ff00ff">
            <xsl:value­of select="artist"/></td>
          </xsl:when>
          <xsl:when test="price &gt; 9">
            <td bgcolor="#cccccc">
            <xsl:value­of select="artist"/></td>
          </xsl:when>
          <xsl:otherwise>
            <td><xsl:value­of select="artist"/></td>
          </xsl:otherwise>
        </xsl:choose>
      </tr>
      </xsl:for­each>
    </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

The code above will add a pink background color to the "Artist" column WHEN the price of the CD is 
higher than 10, and a grey background­color WHEN the price of the CD is higher than 9 and lower or equal 
to 10.

The result of the transformation will look like this:

My CD Collection

Title Artist
Empire Burlesque Bob Dylan
Hide your heart Bonnie Tyler
Greatest Hits Dolly Parton
Still got the blues Gary Moore
Eros Eros Ramazzotti
One night only Bee Gees
Sylvias Mother Dr.Hook
Maggie May Rod Stewart
Romanza Andrea Bocelli
When a man loves a woman Percy Sledge
Black angel Savage Rose
1999 Grammy Nominees Many
For the good times Kenny Rogers
Big Willie style Will Smith
Tupelo Honey Van Morrison
Soulsville Jorn Hoel
The very best of Cat Stevens
Stop Sam Brown
Bridge of Spies T`Pau
Private Dancer Tina Turner
Midt om natten Kim Larsen
Pavarotti Gala Concert Luciano Pavarotti
The dock of the bay Otis Redding
Picture book Simply Red
Red The Communards
Unchain my heart Joe Cocker

XSLT <xsl:apply­templates> Element

The <xsl:apply­templates> element applies a template to the current element or to the current element's 
child nodes.

The <xsl:apply­templates> Element

The <xsl:apply­templates> element applies a template to the current element or to the current element's 
child nodes.

If we add a select attribute to the <xsl:apply­templates> element it will process only the child element that 
matches the value of the attribute. We can use the select attribute to specify the order in which the child 
nodes are processed.

Look at the following XSL style sheet:

<?xml version="1.0" encoding="ISO­8859­1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2> 
<xsl:apply­templates/> 
</body>
</html>
</xsl:template>
<xsl:template match="cd">
<p>
<xsl:apply­templates select="title"/> 
<xsl:apply­templates select="artist"/>
</p>
</xsl:template>
<xsl:template match="title">
Title: <span style="color:#ff0000">
<xsl:value­of select="."/></span>
<br />
</xsl:template>
<xsl:template match="artist">
Artist: <span style="color:#00ff00">
<xsl:value­of select="."/></span>
<br />
</xsl:template>
</xsl:stylesheet>

The result of the transformation will look like this:

My CD Collection

Title: Empire Burlesque
Artist: Bob Dylan

Title: Hide your heart
Artist: Bonnie Tyler

Title: Greatest Hits
Artist: Dolly Parton

Title: Still got the blues
Artist: Gary Moore

Title: Eros
Artist: Eros Ramazzotti

Title: One night only
Artist: Bee Gees

Title: Sylvias Mother
Artist: Dr.Hook

Title: Maggie May
Artist: Rod Stewart
Title: Romanza
Artist: Andrea Bocelli

Title: When a man loves a woman
Artist: Percy Sledge

Title: Black angel
Artist: Savage Rose

Title: 1999 Grammy Nominees
Artist: Many

Title: For the good times
Artist: Kenny Rogers

Title: Big Willie style
Artist: Will Smith

Title: Tupelo Honey
Artist: Van Morrison

Title: Soulsville
Artist: Jorn Hoel

Title: The very best of
Artist: Cat Stevens

Title: Stop
Artist: Sam Brown

Title: Bridge of Spies
Artist: T`Pau

Title: Private Dancer
Artist: Tina Turner

Title: Midt om natten
Artist: Kim Larsen

Title: Pavarotti Gala Concert
Artist: Luciano Pavarotti

Title: The dock of the bay
Artist: Otis Redding

Title: Picture book
Artist: Simply Red

Title: Red
Artist: The Communards
Title: Unchain my heart
Artist: Joe Cocker

XSLT ­ On the Client

If your browser supports it, XSLT can be used to transform the document to XHTML in your browser.

A JavaScript Solution

In the previous chapters we have explained how XSLT can be used to transform a document from XML to 
XHTML. We did this by adding an XSL style sheet to the XML file and let the browser do the 
transformation.

Even if this works fine, it is not always desirable to include a style sheet reference in an XML file (e.g. it 
will not work in a non XSLT aware browser.)

A more versatile solution would be to use a JavaScript to do the transformation.

By using a JavaScript, we can:

• do browser­specific testing
• use different style sheets according to browser and user needs

That is the beauty of XSLT! One of the design goals for XSLT was to make it possible to transform data 
from one format to another, supporting different browsers and different user needs.

XSLT transformation on the client side is bound to be a major part of the browsers work tasks in the future, 
as we will see a growth in the specialized browser market (Braille, aural browsers, Web printers, handheld 
devices, etc.) 

The XML File and the XSL File

Look at the XML document that you have seen in the previous chapters:

<?xml version="1.0" encoding="ISO­8859­1"?>
<catalog>
  <cd>
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>10.90</price>
    <year>1985</year>
  </cd>
.
.
.
</catalog>

And the accompanying XSL style sheet:
<?xml version="1.0" encoding="ISO­8859­1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <html>
  <body>
    <h2>My CD Collection</h2> 
    <table border="1">
      <tr bgcolor="#9acd32">
        <th align="left">Title</th> 
        <th align="left">Artist</th> 
      </tr>
      <xsl:for­each select="catalog/cd">
      <tr>
        <td><xsl:value­of select="title" /></td>
        <td><xsl:value­of select="artist" /></td>
      </tr>
      </xsl:for­each>
  </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

Notice that the XML file does not have a reference to the XSL file.

IMPORTANT: The above sentence indicates that an XML file could be transformed using many different 
XSL style sheets.

Transforming XML to XHTML in the Browser

Here is the source code needed to transform the XML file to XHTML on the client:

<html>
<head>
<script>
function loadXMLDoc(fname)
{
var xmlDoc;
// code for IE
if (window.ActiveXObject)
  {
  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  }
// code for Mozilla, Firefox, Opera, etc.
else if (document.implementation 
&& document.implementation.createDocument)
  {
  xmlDoc=document.implementation.createDocument("","",null);
  }
else
  {
  alert('Your browser cannot handle this script');
  }
xmlDoc.async=false;
xmlDoc.load(fname);
return(xmlDoc);
}

function displayResult()
{
xml=loadXMLDoc("cdcatalog.xml");
xsl=loadXMLDoc("cdcatalog.xsl");
// code for IE
if (window.ActiveXObject)
  {
  ex=xml.transformNode(xsl);
  document.getElementById("example").innerHTML=ex;
  }
// code for Mozilla, Firefox, Opera, etc.
else if (document.implementation 
&& document.implementation.createDocument)
  {
  xsltProcessor=new XSLTProcessor();
  xsltProcessor.importStylesheet(xsl);
  resultDocument = xsltProcessor.transformToFragment(xml,document);
  document.getElementById("example").appendChild(resultDocument);
  }
}
</script>
</head>
<body id="example" onLoad="displayResult()">
</body>
</html>

Example Explained:

The loadXMLDoc() Function

The loadXMLDoc() function is used to load the XML and XSL files.

It checks what kind of browser the user has and loads the file.

The displayResult() Function

This function is used to display the XML file styled by the XSL file.

• Load XML and XSL file
• Test what kind of browser the user has
• If the user has a browser supporting the ActiveX object:
o Use the transformNode() method to apply the XSL style sheet to the xml document
o Set the body of the current document (id="example") to contain the styled xml document
• If the user has a browser that does not support the ActiveX object:
o Create a new XSLTProcessor object and import the XSL file to it
o Use the transformToFragment() method to apply the XSL style sheet to the xml document
o Set the body of the current document (id="example") to contain the styled xml document

XSLT ­ On the Server

Since not all browsers support XSLT, one solution is to transform the XML to XHTML on the server.

A Cross Browser Solution

In the previous chapter we explained how XSLT can be used to transform a document from XML to 
XHTML in the browser. We created a JavaScript that used an XML parser to do the transformation. The 
JavaScript solution will not work in a browser that doesn't have an XML parser.

To make XML data available to all kind of browsers, we must transform the XML document on the 
SERVER and send it as XHTML back to the browser.

That's another beauty of XSLT. One of the design goals for XSLT was to make it possible to transform data 
from one format to another on a server, returning readable data to all kinds of browsers.

The XML File and the XSLT File

Look at the XML document that you have seen in the previous chapters:

<?xml version="1.0" encoding="ISO­8859­1"?>
<catalog>
  <cd>
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>10.90</price>
    <year>1985</year>
  </cd>
.
.
.
</catalog>

And the accompanying XSL style sheet:

<?xml version="1.0" encoding="ISO­8859­1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <html>
  <body>
    <h2>My CD Collection</h2> 
    <table border="1">
      <tr bgcolor="#9acd32">
        <th align="left">Title</th> 
        <th align="left">Artist</th> 
      </tr>
      <xsl:for­each select="catalog/cd">
      <tr>
        <td><xsl:value­of select="title" /></td>
        <td><xsl:value­of select="artist" /></td>
      </tr>
      </xsl:for­each>
  </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

Notice that the XML file does not have a reference to the XSL file.

IMPORTANT: The above sentence indicates that an XML file could be transformed using many different 
XSL style sheets.

Transforming XML to XHTML on the Server

Here is the ASP source code needed to transform the XML file to XHTML on the server:

<%
'Load XML
set xml = Server.CreateObject("Microsoft.XMLDOM")
xml.async = false
xml.load(Server.MapPath("cdcatalog.xml"))

'Load XSL
set xsl = Server.CreateObject("Microsoft.XMLDOM")
xsl.async = false
xsl.load(Server.MapPath("cdcatalog.xsl"))

'Transform file
Response.Write(xml.transformNode(xsl))
%>

The first block of code creates an instance of the Microsoft XML parser (XMLDOM), and loads the XML 
file into memory. The second block of code creates another instance of the parser and loads the XSL file 
into memory. The last line of code transforms the XML document using the XSL document, and sends the 
result as XHTML to your browser. Nice!

XSLT ­ Editing XML

Data stored in XML files can be edited from an Internet browser.
Open, Edit and Save XML

Now, we will show how to open, edit, and save an XML file that is stored on the server.

We will use XSL to transform the XML document into an HTML form. The values of the XML elements 
will be written to HTML input fields in an HTML form. The HTML form is editable. After editing the data, 
the data is going to be submitted back to the server and the XML file will be updated (this part is done with 
ASP). 

The XML File and the XSL File

First, look at the XML document that will be used ("tool.xml"):

<?xml version="1.0" encoding="ISO­8859­1"?>
<tool>
  <field id="prodName">
    <value>HAMMER HG2606</value> 
  </field>
  <field id="prodNo">
    <value>32456240</value> 
  </field>
  <field id="price">
    <value>$30.00</value> 
  </field>
</tool>

Then, take a look at the following style sheet ("tool.xsl"):

<?xml version="1.0" encoding="ISO­8859­1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<form method="post" action="edittool.asp">
<h2>Tool Information (edit):</h2>
<table border="0">
<xsl:for­each select="tool/field">
<tr>
<td>
<xsl:value­of select="@id"/>
</td>
<td>
<input type="text">
<xsl:attribute name="id">
  <xsl:value­of select="@id" />
</xsl:attribute>
<xsl:attribute name="name">
  <xsl:value­of select="@id" />
</xsl:attribute>
<xsl:attribute name="value">
  <xsl:value­of select="value" />
</xsl:attribute>
</input> 
</td>
</tr>
</xsl:for­each>
</table>
<br />
<input type="submit" id="btn_sub" name="btn_sub" value="Submit" />
<input type="reset" id="btn_res" name="btn_res" value="Reset" />
</form>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

The XSL file above loops through the elements in the XML file and creates one input field for each XML 
"field" element. The value of the XML "field" element's "id" attribute is added to both the "id" and "name" 
attributes of each HTML input field. The value of each XML "value" element is added to the "value" 
attribute of each HTML input field. The result is an editable HTML form that contains the values from the 
XML file.

Then, we have a second style sheet: "tool_updated.xsl". This is the XSL file that will be used to display the 
updated XML data. This style sheet will not result in an editable HTML form, but a static HTML table:

<?xml version="1.0" encoding="ISO­8859­1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>Updated Tool Information:</h2>
<table border="1">
<xsl:for­each select="tool/field">
<tr>
<td><xsl:value­of select="@id" /></td>
<td><xsl:value­of select="value" /></td>
</tr>
</xsl:for­each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

The ASP File

The HTML form in the "tool.xsl" file above has an action attribute with a value of "edittool.asp".

The "edittool.asp" page contains two functions: The loadFile() function loads and transforms the XML file 
for display and the updateFile() function applies the changes to the XML file:

<%
function loadFile(xmlfile,xslfile)
Dim xmlDoc,xslDoc
'Load XML file
set xmlDoc = Server.CreateObject("Microsoft.XMLDOM")
xmlDoc.async = false
xmlDoc.load(xmlfile)
'Load XSL file
set xslDoc = Server.CreateObject("Microsoft.XMLDOM")
xslDoc.async = false
xslDoc.load(xslfile)
'Transform file
Response.Write(xmlDoc.transformNode(xslDoc))
end function
function updateFile(xmlfile)
Dim xmlDoc,rootEl,f
Dim i
'Load XML file
set xmlDoc = Server.CreateObject("Microsoft.XMLDOM")
xmlDoc.async = false
xmlDoc.load(xmlfile)
'Set the rootEl variable equal to the root element
Set rootEl = xmlDoc.documentElement
'Loop through the form collection
for i = 1 To Request.Form.Count
  'Eliminate button elements in the form
  if instr(1,Request.Form.Key(i),"btn_")=0 then
    'The selectSingleNode method queries the XML file for a 
    'single node that matches a query. This query requests
    'the value element that is the child of a field element
    'that has an id attribute which matches the current key
    'value in the Form Collection. When there is a match ­
    'set the text property equal to the value of the current
    'field in the Form Collection.
    set f = rootEl.selectSingleNode("field[@id='" & _
    Request.Form.Key(i) & "']/value")
    f.Text = Request.Form(i)
  end if
next
'Save the modified XML file
xmlDoc.save xmlfile
'Release all object references
set xmlDoc=nothing
set rootEl=nothing
set f=nothing
'Load the modified XML file with a style sheet that
'allows the client to see the edited information
loadFile xmlfile,server.MapPath("tool_updated.xsl")
end function
'If the form has been submitted update the
'XML file and display result ­ if not,
'transform the XML file for editing
if Request.Form("btn_sub")="" then
loadFile server.MapPath("tool.xml"),server.MapPath("tool.xsl")
else
updateFile server.MapPath("tool.xml")
end if
%>

Note: We are doing the transformation and applying the changes to the XML file on the server. This is a 
cross­browser solution. The client will only get HTML back from the server ­ which will work in any 
browser.

XML Editors

If you are serious about XML, you will benefit from using a professional XML Editor.

XML is Text­based
XML is a text­based markup language.
One great thing about XML is that XML files can be created and edited using a simple text­editor like 
Notepad.
However, when you start working with XML, you will soon find that it is better to edit XML documents 
using a professional XML editor.
Why Not Notepad?
Many web developers use Notepad to edit both HTML and XML documents because Notepad is included 
with the most common OS and it is simple to use. Personally I often use Notepad for quick editing of 
simple HTML, CSS, and XML files.
But, if you use Notepad for XML editing, you will soon run into problems.
Notepad does not know that you are writing XML, so it will not be able to assist you. 

Why an XML Editor?

Today XML is an important technology, and development projects use XML­based technologies like:

• XML Schema to define XML structures and data types
• XSLT to transform XML data
• SOAP to exchange XML data between applications
• WSDL to describe web services
• RDF to describe web resources
• XPath and XQuery to access XML data
• SMIL to define graphics

To be able to write error­free XML documents, you will need an intelligent XML editor!

XML Editors

Professional XML editors will help you to write error­free XML documents, validate your XML against a 
DTD or a schema, and force you to stick to a valid XML structure.

An XML editor should be able to:

• Add closing tags to your opening tags automatically
• Force you to write valid XML
• Verify your XML against a DTD
• Verify your XML against a Schema
• Color code your XML syntax
Altova® XMLSpy®

At W3Schools we have been using XMLSpy for many years. XMLSpy is our favorite XML editor. These 
are some of the features we especially like:

• Easy to use
• Automatic tag completion
• Context­sensitive entry helpers
• Automatic well­formedness checking
• Syntax coloring and pretty printing
• Built in DTD and/or XML Schema­based validation
• Easy switching between text view and grid view
• Built in graphical XML Schema editor
• Powerful conversion utilities
• Database import and export
• Built in templates for many XML document types
• Built in XPath 1.0/2.0 analyzer
• XSLT 1.0/2.0 editor, profiler, and debugger
• XQuery editor, profiler, and debugger
• SOAP client and debugger
• Graphical WSDL editor
• Powerful project management capabilities
• Code generation in Java, C++, and C#
• Support for Office 2007 / OOXML

XSLT Elements Reference

The XSLT elements from the W3C Recommendation (XSLT Version 1.0).

XSLT Elements

The links in the "Element" column point to attributes and more useful information about each specific 
element.

• FF: indicates the earliest version of Firefox that supports the tag 
• IE: indicates the earliest version of Internet Explorer that supports the tag

Note: Elements supported in IE 5 may have NON­standard behavior, because IE 5 was released before 
XSLT became an official W3C Recommendation.

Element Description IE FF
apply­imports Applies a template rule from an imported style sheet 6.0 1.0
apply­templates Applies a template rule to the current element or to the  5.0 1.0
current element's child nodes
attribute Adds an attribute 5.0 1.0
attribute­set Defines a named set of attributes 6.0 1.0
call­template Calls a named template 6.0 1.0
choose Used in conjunction with <when> and <otherwise> to  5.0 1.0
express multiple conditional tests
comment Creates a comment node in the result tree 5.0 1.0
copy Creates a copy of the current node (without child nodes  5.0 1.0
and attributes)
copy­of Creates a copy of the current node (with child nodes and  6.0 1.0
attributes)
decimal­format Defines the characters and symbols to be used when  6.0 1.0
converting numbers into strings, with the format­number() 
function
element Creates an element node in the output document 5.0 1.0
fallback Specifies an alternate code to run if  the processor does not  6.0  
support an XSLT element
for­each Loops through each node in a specified node set 5.0 1.0
if Contains a template that will be applied only if a specified  5.0 1.0
condition is true
import Imports the contents of one style sheet into another. Note:  6.0 1.0
An imported style sheet has lower precedence than the 
importing style sheet
include Includes the contents of one style sheet into another. Note:  6.0 1.0
An included style sheet has the same precedence as the 
including style sheet
key Declares a named key that can be used in the style sheet  6.0 1.0
with the key() function
message Writes a message to the output (used to report errors) 6.0 1.0
namespace­alias Replaces a namespace in the style sheet to a different  6.0  
namespace in the output
number Determines the integer position of the current node and  6.0 1.0
formats a number
otherwise Specifies a default action for the <choose> element 5.0 1.0
output Defines the format of the output document 6.0 1.0
param Declares a local or global parameter 6.0 1.0
preserve­space Defines the elements for which white space should be  6.0 1.0
preserved
processing­instruction Writes a processing instruction to the output 5.0 1.0
sort Sorts the output 6.0 1.0
strip­space Defines the elements for which white space should be  6.0 1.0
removed
stylesheet Defines the root element of a style sheet 5.0 1.0
template Rules to apply when a specified node is matched 5.0 1.0
text Writes literal text to the output 5.0 1.0
transform Defines the root element of a style sheet 6.0 1.0
value­of Extracts the value of a selected node 5.0 1.0
variable Declares a local or global variable 6.0 1.0
when Specifies an action for the <choose> element 5.0 1.0
with­param Defines the value of a parameter to be passed into a  6.0 1.0
template

XSLT Functions

XQuery 1.0, XPath 2.0, and XSLT 2.0 share the same functions library.

XSLT Functions

XSLT includes over 100 built­in functions. There are functions for string values, numeric values, date and 
time comparison, node and QName manipulation, sequence manipulation, Boolean values, and more.

The URI of the XSLT function namespace is:
http://www.w3.org/2005/02/xpath­functions

The default prefix for the function namespace is fn:.

Tip: Functions are often called with the fn: prefix, such as fn:string(). However, since fn: is the default 
prefix of the namespace, the function names do not need to be prefixed when called.

The reference of all the built­in XSLT 2.0 functions is located in our XPath tutorial.

In addition, there are the following built­in XSLT functions:

Name Description
current() Returns the current node
document() Used to access the nodes in an external XML document
element­available() Tests whether the element specified is supported by the XSLT processor
format­number() Converts a number into a string
function­available() Tests whether the function specified is supported by the XSLT processor
generate­id() Returns a string value that uniquely identifies a specified node
key() Returns a node­set using the index specified by an <xsl:key> element
system­property() Returns the value of the system properties
unparsed­entity­uri() Returns the URI of an unparsed entity

XSL­FO Tutorial

In our XSL­FO tutorial you will learn what XSL­FO is.
You will learn how to use XSL­FO to format your XML documents for output.

Introduction to XSL­FO

XSL­FO is about formatting XML data for output.

What You Should Already Know

Before you study XSL­FO you should have a basic understanding of XML and XML Namespaces.

What is XSL­FO?

• XSL­FO is a language for formatting XML data
• XSL­FO stands for Extensible Stylesheet Language Formatting Objects
• XSL­FO is a W3C Recommendation
• XSL­FO is now formally named XSL

XSL­FO is About Formatting

XSL­FO is an XML­based markup language describing the formatting of XML data for output to screen, 
paper or other media.

XSL­FO is Formally Named XSL

Why this confusion? Is XSL­FO and XSL the same thing?

Yes it is, but we will give you an explanation:

Styling is both about transforming and formatting information. When the World Wide Web Consortium 
(W3C) made their first XSL Working Draft, it contained the language syntax for both transforming and 
formatting XML documents.

Later, the XSL Working Group at W3C split the original draft into separate Recommendations:

• XSLT, a language for transforming XML documents
• XSL or XSL­FO, a language for formatting XML documents
• XPath, a language for navigating through elements and attributes in XML documents

The rest of this tutorial is about formatting XML documents: XSL­FO, also called XSL. 

XSL­FO is a Web Standard

XSL­FO became a W3C Recommendation 15. October 2001. Formally named XSL.

XSL­FO Documents
XSL­FO documents are XML files with output information.
XSL­FO Documents
XSL­FO documents are XML files with output information. They contain information about the output 
layout and output contents.
XSL­FO documents are stored in files with a .fo or a .fob file extension. It is also quite common to see 
XSL­FO documents stored with an .xml extension, because this makes them more accessible to XML 
editors.
XSL­FO Document Structure
XSL­FO documents have a structure like this:
<?xml version="1.0" encoding="ISO­8859­1"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">

<fo:layout­master­set>
  <fo:simple­page­master master­name="A4">
    <!­­ Page template goes here ­­>
  </fo:simple­page­master>
</fo:layout­master­set>

<fo:page­sequence master­reference="A4">
  <!­­ Page content goes here ­­>
</fo:page­sequence>
</fo:root>

Structure explained

XSL­FO documents are XML documents, and must always start with an XML declaration:

<?xml version="1.0" encoding="ISO­8859­1"?>

The <fo:root> element is the root element of XSL­FO documents. The root element also declares the 
namespace for XSL­FO:

<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
  <!­­ The full XSL­FO document goes here ­­>
</fo:root>

The <fo:layout­master­set> element contains one or more page templates:

<fo:layout­master­set>
  <!­­ All page templates go here ­­>
</fo:layout­master­set>

Each <fo:simple­page­master> element contains a single page template. Each template must have a unique 
name (master­name):

<fo:simple­page­master master­name="A4">
  <!­­ One page template goes here ­­>
</fo:simple­page­master>

One or more <fo:page­sequence> elements describe the page contents. The master­reference attribute refers 
to the simple­page­master template with the same name:

<fo:page­sequence master­reference="A4">
  <!­­ Page content goes here ­­>
</fo:page­sequence>

XSL­FO Areas

XSL­FO uses rectangular boxes (areas) to display output.

XSL­FO Areas

The XSL formatting model defines a number of rectangular areas (boxes) to display output.

All output (text, pictures, etc.) will be formatted into these boxes and then displayed or printed to a target 
media.

We will take a closer look at the following areas:

• Pages
• Regions
• Block areas
• Line areas
• Inline areas

XSL­FO Pages

XSL­FO output is formatted into pages. Printed output will normally go into many separate pages. Browser 
output will often go into one long page.

XSL­FO Pages contain Regions.

XSL­FO Regions

Each XSL­FO Page contains a number of Regions:

• region­body (the body of the page)
• region­before (the header of the page)
• region­after (the footer of the page)
• region­start (the left sidebar)
• region­end (the right sidebar)

XSL­FO Regions contain Block areas.
XSL­FO Block Areas

XSL­FO Block areas define small block elements (the ones that normally starts with a new line) like 
paragraphs, tables and lists.

XSL­FO Block areas can contain other Block areas, but most often they contain Line areas.

XSL­FO Line Areas

XSL­FO Line areas define text lines inside Block areas.

XSL­FO Line areas contain Inline areas.

XSL­FO Inline Areas

XSL­FO Inline areas define text inside Lines (bullets, single character, graphics, and more).

XSL­FO Output

XSL­FO defines output inside <fo:flow> elements.

XSL­FO Page, Flow, and Block

"Blocks" of content "Flows" into "Pages" and then to the output media.

XSL­FO output is normally nested inside <fo:block> elements, nested inside <fo:flow> elements, nested 
inside <fo:page­sequence> elements:

<fo:page­sequence>
  <fo:flow flow­name="xsl­region­body">
    <fo:block>
      <!­­ Output goes here ­­>
    </fo:block>
  </fo:flow>
</fo:page­sequence>

XSL­FO Example

It is time to look at a real XSL­FO example:

<?xml version="1.0" encoding="ISO­8859­1"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">

<fo:layout­master­set>
  <fo:simple­page­master master­name="A4">
    <fo:region­body />
  </fo:simple­page­master>
</fo:layout­master­set>
<fo:page­sequence master­reference="A4">
  <fo:flow flow­name="xsl­region­body">
    <fo:block>Hello W3Schools</fo:block>
  </fo:flow>
</fo:page­sequence>
</fo:root>

XSL­FO Flow

XSL­FO pages are filled with data from <fo:flow> elements.

XSL­FO Page Sequences

XSL­FO uses <fo:page­sequence> elements to define output pages.

Each output page refers to a page master which defines the layout.

Each output page has a <fo:flow> element defining the output.

Each output page is printed (or displayed) in sequence.

XSL­FO Flow

XSL­FO pages are filled with content from the <fo:flow> element.

The <fo:flow> element contains all the elements to be printed to the page.

When the page is full, the same page master will be used over (and over) again until all the text is printed.

Where To Flow?

The <fo:flow> element has a "flow­name" attribute.

The value of the flow­name attribute defines where the content of the <fo:flow> element will go.

The legal values are:

• xsl­region­body (into the region­body)
• xsl­region­before (into the region­before)
• xsl­region­after (into the region­after)
• xsl­region­start (into the region­start)
• xsl­region­end (into the region­end)

XSL­FO Pages

XSL­FO uses page templates called "Page Masters" to define the layout of  pages.

XSL­FO Page Templates
XSL­FO uses page templates called "Page Masters" to define the layout of  pages. Each template must have 
a unique name:

<fo:simple­page­master master­name="intro">
  <fo:region­body margin="5in" />
</fo:simple­page­master>
<fo:simple­page­master master­name="left">
  <fo:region­body margin­left="2in" margin­right="3in" />
</fo:simple­page­master>
<fo:simple­page­master master­name="right">
  <fo:region­body margin­left="3in" margin­right="2in" />
</fo:simple­page­master>

In the example above, three <fo:simple­page­master> elements, define three different templates. Each 
template (page­master) has a different name.

The first template is called "intro". It could be used as a template for introduction pages.

The second and third templates are called "left" and "right". They could be used as templates for even and 
odd page numbers.

XSL­FO Page Size

XSL­FO uses the following attributes to define the size of a page:

• page­width defines the width of a page
• page­height defines the height of a page

XSL­FO Page Margins

XSL­FO uses the following attributes to define the margins of a page:

• margin­top defines the top margin
• margin­bottom defines the bottom margin
• margin­left defines the left margin
• margin­right defines the right margin
• margin defines all four margins

XSL­FO Page Regions

XSL­FO uses the following elements to define the regions of a page:

• region­body defines the body region
• region­before defines the top region (header)
• region­after defines the bottom region (footer)
• region­start defines the left region (left sidebar)
• region­end defines the right region (right sidebar)
Note that the region­before, region­after, region­start, and region­end is a part of the body region. To avoid 
text in the body region to overwrite text in these regions, the body region must have margins at least the 
size of these regions. 

Margin Top

REGION BEFORE

 
R
M   M
E R
a a
r G E r
 
g I G g
i O I i
REGION BODY
n N O n
N
 
L S R
e T E i
f   g
A N
t D h
R
    t
T
 

REGION AFTER

Margin Bottom

XSL­FO Example

This is an extract from an XSL­FO document:

<fo:simple­page­master master­name="A4"
 page­width="297mm" page­height="210mm"
 margin­top="1cm"   margin­bottom="1cm"
 margin­left="1cm"  margin­right="1cm">
  <fo:region­body   margin="3cm"/>
  <fo:region­before extent="2cm"/>
  <fo:region­after  extent="2cm"/>
  <fo:region­start  extent="2cm"/>
  <fo:region­end    extent="2cm"/>
</fo:simple­page­master>

The code above defines a "Simple Page Master Template" with the name "A4".

The width of the page is 297 millimeters and the height is 210 millimeters.

The top, bottom, left, and right margins of the page are all 1 centimeter.

The body has a 3 centimeter margin (on all sides).

The before, after, start, and end regions (of the body) are all 2 centimeters.

The width of the body in the example above can be calculated by subtracting the left and right margins and 
the region­body margins from the width of the page itself:

297mm ­ (2 x 1cm) ­ (2 x 3cm) = 297mm ­ 20mm ­ 60mm = 217mm.

Note that the regions (region­start and region­end) are not a part of the calculation. As described earlier, 
these regions are parts of the body. 

XSL­FO Blocks

XSL­FO output goes into blocks.

XSL­FO Pages, Flow, and Block

"Blocks" of content "Flow" into "Pages" of the output media.

XSL­FO output is normally nested inside <fo:block> elements,  nested inside <fo:flow> elements, nested 
inside <fo:page­sequence> elements:

<fo:page­sequence>
  <fo:flow flow­name="xsl­region­body">
    <fo:block>
      <!­­ Output goes here ­­>
    </fo:block>
  </fo:flow>
</fo:page­sequence>

Block Area Attributes

Blocks are sequences of output in rectangular boxes:
<fo:block
  border­width="1mm">
This block of output will have a one millimeter border around it.
</fo:block>

Since block areas are rectangular boxes, they share many common area properties: 

• space before and space after
• margin
• border
• padding

space before
margin
border
padding

content

space after

The space before and space after is the empty space separating the block from the other blocks.

The margin is the empty area on the outside of the block.  

The border is the rectangle drawn around the external edge of the area. It can have different widths on all 
four sides. It can also be filled with different colors and background images.

The padding is the area between the border and the content area.

The content area contains the actual content like text, pictures, graphics, or whatever.

Block Margin

• margin
• margin­top
• margin­bottom
• margin­left
• margin­right

Block Border
Border style attributes:

• border­style
• border­before­style
• border­after­style
• border­start­style
• border­end­style
• border­top­style (same as border­before)
• border­bottom­style (same as border­after)
• border­left­style (same as border­start)
• border­right­style (same as border­end)

Border color attributes:

• border­color
• border­before­color
• border­after­color
• border­start­color
• border­end­color
• border­top­color (same as border­before)
• border­bottom­color (same as border­after)
• border­left­color (same as border­start)
• border­right­color (same as border­end)

Border width attributes:

• border­width
• border­before­width
• border­after­width
• border­start­width
• border­end­width
• border­top­width (same as border­before)
• border­bottom­width (same as border­after)
• border­left­width (same as border­start)
• border­right­width (same as border­end)

Block Padding

• padding
• padding­before
• padding­after
• padding­start
• padding­end
• padding­top (same as padding­before)
• padding­bottom (same as padding­after)
• padding­left (same as padding­start)
• padding­right (same as padding­end)
Block Background

• background­color
• background­image
• background­repeat 
• background­attachment (scroll or fixed)

Block Styling Attributes

Blocks are sequences of output that can be styled individually:

<fo:block
  font­size="12pt"
  font­family="sans­serif">
This block of output will be written in a 12pt sans­serif font.
</fo:block>

Font attributes:

• font­family
• font­weight
• font­style
• font­size
• font­variant

Text attributes:

• text­align
• text­align­last
• text­indent
• start­indent
• end­indent 
• wrap­option (defines word wrap)
• break­before (defines page breaks)
• break­after (defines page breaks)
• reference­orientation (defines text rotation in 90" increments) 

Example

<fo:block
    font­size="14pt" font­family="verdana" color="red"
    space­before="5mm" space­after="5mm">
W3Schools
</fo:block>
<fo:block
    text­indent="5mm"
    font­family="verdana" font­size="12pt"
    space­before="5mm" space­after="5mm">
At W3Schools you will find all the Web­building tutorials you
need, from basic HTML and XHTML to advanced XML, XSL, Multimedia
and WAP.
</fo:block>

Result:

W3Schools

   At W3Schools you will find all the Web­building 
tutorials you need, from basic HTML and XHTML 
to advanced XML, XSL, Multimedia and WAP.
 

When you look at the example above, you can see that it will take a lot of code to produce a document with 
many headers and paragraphs.

Normally XSL­FO document do not combine formatting information and content like we have done here.

With a little help from XSLT we can put the formatting information into templates and write a cleaner 
content.

You will learn more about how to combine XSL­FO with XSLT templates in a later chapter in this tutorial.

XSL­FO Lists

XSL­FO uses List Blocks to define lists.

XSL­FO List Blocks

There are four XSL­FO objects used to create lists: 

• fo:list­block (contains the whole list)
• fo:list­item (contains each item in the list)
• fo:list­item­label (contains the label for the list­item ­ typically an <fo:block> containing a 
number, character, etc.)
• fo:list­item­body (contains the content/body of the list­item ­ typically one or more <fo:block> 
objects)

An XSL­FO list example:

<fo:list­block>
<fo:list­item>
 <fo:list­item­label>
   <fo:block>*</fo:block>
 </fo:list­item­label>
 <fo:list­item­body>
   <fo:block>Volvo</fo:block>
 </fo:list­item­body>
</fo:list­item>
<fo:list­item>
 <fo:list­item­label>
   <fo:block>*</fo:block>
 </fo:list­item­label>
 <fo:list­item­body>
   <fo:block>Saab</fo:block>
 </fo:list­item­body>
</fo:list­item>
</fo:list­block>

The output from this code would be:

 * Volvo
 * Saab
 

XSL­FO Tables

XSL­FO uses the <fo:table­and­caption> element to define tables.

XSL­FO Tables

The XSL­FO table model is not very different from the HTML table model.
There are nine XSL­FO objects used to create tables:
• fo:table­and­caption
• fo:table
• fo:table­caption
• fo:table­column
• fo:table­header
• fo:table­footer
• fo:table­body
• fo:table­row
• fo:table­cell
XSL­FO uses the <fo:table­and­caption> element to define a table. It contains a <fo:table> and an 
optional <fo:caption> element.
The <fo:table> element contains optional <fo:table­column> elements, an optional <fo:table­header> 
element, a <fo:table­body> element, and an optional <fo:table­footer> element. Each of these elements 
has one or more <fo:table­row> elements, with one or more <fo:table­cell> elements:
<fo:table­and­caption>
<fo:table>
<fo:table­column column­width="25mm"/>
<fo:table­column column­width="25mm"/>

<fo:table­header>
  <fo:table­row>
    <fo:table­cell>
      <fo:block font­weight="bold">Car</fo:block>
    </fo:table­cell>
    <fo:table­cell>
      <fo:block font­weight="bold">Price</fo:block>
    </fo:table­cell>
  </fo:table­row>
</fo:table­header>

<fo:table­body>
  <fo:table­row>
    <fo:table­cell>
      <fo:block>Volvo</fo:block>
    </fo:table­cell>
    <fo:table­cell>
      <fo:block>$50000</fo:block>
    </fo:table­cell>
  </fo:table­row>
  <fo:table­row>
    <fo:table­cell>
      <fo:block>SAAB</fo:block>
    </fo:table­cell>
    <fo:table­cell>
      <fo:block>$48000</fo:block>
    </fo:table­cell>
  </fo:table­row>
</fo:table­body>

</fo:table>
</fo:table­and­caption>

The output from this code would something like this:

Car Price

Volvo $50000

SAAB $48000
XSL­FO and XSLT

XSL­FO and XSLT can help each other.

Remember this Example?

<fo:block
    font­size="14pt" font­family="verdana" color="red"
    space­before="5mm" space­after="5mm">
W3Schools
</fo:block>
<fo:block
    text­indent="5mm"
    font­family="verdana" font­size="12pt"
    space­before="5mm" space­after="5mm">
At W3Schools you will find all the Web­building tutorials you
need, from basic HTML and XHTML to advanced XML, XSL, Multimedia
and WAP.
</fo:block>

Result:

W3Schools

   At W3Schools you will find all the Web­building 
tutorials you need, from basic HTML and XHTML 
to advanced XML, XSL, Multimedia and WAP.
 

The example above is from the chapter about XSL­FO Blocks.

With a Little Help from XSLT
Remove the XSL­FO information from the document:
<header>
W3Schools
</header>
<paragraph>
At W3Schools you will find all the Web­building tutorials you
need, from basic HTML and XHTML to advanced XML, XSL, Multimedia
and WAP.
</paragraph>

Add an XSLT transformation:

<xsl:template match="header">
<fo:block
    font­size="14pt" font­family="verdana" color="red"
    space­before="5mm" space­after="5mm">
    <xsl:apply­templates/>
</fo:block>
</xsl:template>

<xsl:template match="paragraph">
<fo:block
    text­indent="5mm"
    font­family="verdana" font­size="12pt"
    space­before="5mm" space­after="5mm">
    <xsl:apply­templates/>
</fo:block>
</xsl:template>

And the result will be the same:

W3Schools

   At W3Schools you will find all the Web­building 
tutorials you need, from basic HTML and XHTML 
to advanced XML, XSL, Multimedia and WAP.
 

XSL­FO Software

XSL­FO needs formatting software to produce output.

XSL­FO Processors

An XSL­FO processor is a software program for formatting XSL documents for output.

Most XSL­FO processors can output PDF documents and quality print, as well as HTML and other formats. 

Some well­known XSL­FO processors are described below.

XSL Formatter

XSL Formatter is a software to format XML documents for production­quality printing and output to PDF.

Antenna House has been providing version V2 of the same product since January, 2002 in the global 
market, and XSL Formatter was rated as one of the best quality product at the XML 2002, XML 2003 
conferences held in Europe.

Building on over 4 years of experience developing XSL­FO software, Antenna House has completely 
written from scratch an entirely new Formatter that offers significant enhancements and provides a solid 
foundation on which to continue to move forward.
Xinc Beta Release

Xinc is an XSL­FO processor by Lunasil LTD.

Xinc is designed to be fast, multithreaded and memory efficient. A Swing based XSL­FO viewer allows 
you to view and print XSL­FO files as well as generate PDF files with the click of a button. Xinc can be 
used as a server component via its Java API. Xinc can also be used in a Microsoft server environment by 
using its COM interface. New features include hyphenation, basic­link, PDF output, memory/speed 
optimizations and a simple COM interface. 

Scriptura

Inventive Designers Scriptura is a cross­platform document design and generation solution based on XSLT 
and XSL­FO. 

Scriptura has a WYSIWYG design tool and engine. The XSL­FO formatter used in the engine is no longer 
based on Apache FOP, but is written from scratch by Inventive Designers. The new features in this release 
are: support for bulleted and numbered lists, 'break­before' and 'break­after' properties, extended bar code 
options and improved number and currency formatting. A free trial version is available for download.

XSL­FO Reference

XSL Formatting Objects Reference

The process that converts a description into a presentation is called formatting.

Object Description
basic­link Represents the start resource of a link
bidi­override Overrides the default Unicode BIDI direction
block Defines a block of output (e.g. paragraphs and titles)
block­container Defines a block­level reference­area
character Specifies a character that will be mapped to a glyph 
for presentation
color­profile Defines a color­profile for a stylesheet
conditional­page­master­reference Specifies a page­master to be used when the 
conditions defined are true
declarations Groups global declarations for a stylesheet
external­graphic Used for a graphic where the graphics data resides 
outside of the XML result tree
float Typically used to position an image in a separate area 
at the beginning of a page OR to position an image to 
one side, with the content flowing along­side of the 
image
flow Contains all elements to be printed to a page
footnote Defines a footnote within the region­body of a page
footnote­body Defines the content of the footnote
initial­property­set Formats the first line of an <fo:block>
inline Formats a part of a text with a background or 
enclosing it in a border
inline­container Defines an inline reference­area
instream­foreign­object Used for inline graphics or for "generic" objects where 
the object's data resides as descendants of 
<fo:instream­foreign­object>
layout­master­set Holds all masters used in a document
leader Used to generate "." to separate titles from page 
numbers in table of contents, or to create input fields 
in forms, or to create horizontal rules
list­block Defines a list
list­item Contains each item in the list
list­item­body Contains the content/body of the list­item
list­item­label Contains the label for the list­item (typically a 
number, character, etc.)
marker Used with <fo:retrieve­marker> to create running 
headers or footers
multi­case Contains (within an <fo:multi­switch>) each 
alternative sub­tree of XSL­FO objects. The parent 
<fo:multi­switch> will choose which alternative to 
show and hide the rest
multi­properties Used to switch between two or more property­sets
multi­property­set Specifies an alternative property­set that will be 
applied depending on the state of the user agent
multi­switch Holds one or more <fo:multi­case> objects and 
controls the switching between them (activated by 
<fo:multi­toggle>)
multi­toggle Used to switch to another <fo:multi­case>
page­number Represents the current page­number
page­number­citation References the page­number for the page that contains 
the first normal area returned by the cited object
page­sequence A container for page output elements. There will be 
one <fo:page­sequence> object for each page layout
page­sequence­master Specifies which simple­page­masters are to be used 
and in which order
region­after Defines a page footer
region­before Defines a page header
region­body Defines a page body
region­end Defines the right sidebar of a page
region­start Defines the left sidebar of a page
repeatable­page­master­alternatives Specifies repetition of a set of simple­page­masters
repeatable­page­master­reference Specifies repetition of a single simple­page­master
retrieve­marker Used with <fo:marker> to create running headers or 
footers
root The root (top) node for XSL­FO documents
simple­page­master Defines the size and shape of a page 
single­page­master­reference Specifies a page­master to be used at a given point in 
the sequence of pages
static­content Contains static content (e.g. headers and footers) that 
will be repeated on many pages
table Formats the tabular material of a table
table­and­caption Formats a table and its caption
table­body Container for table rows and table cells
table­caption Contains the caption for a table
table­cell Defines a table cell
table­column Formats the columns of a table
table­footer Defines a table footer
table­header Defines a table header
table­row Defines a table row
title Defines a title for a page­sequence
wrapper Specifies inherited properties for a group of XSL­FO 
objects

You might also like