XSLT
Student Workbook
Page ii Rev 4.1.1 © 2008 ITCourseware, LLC
XSLT
XSLT
Paul Hoffmann, Jamie Romero, Robert Seitz, and Todd Wright
Published by ITCourseware, LLC, 7245 South Havana Street, Suite 100, Englewood, CO 80112
Technical Editors: Jim Gallentine and Jamie Romero
Copyeditor: Danielle North
Special thanks to: Many instructors whose ideas and careful review have contributed to the quality of this
workbook.
Copyright © 2008 by ITCourseware, LLC. All rights reserved. No part of this book may be reproduced
or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by
an information storage retrieval system, without permission in writing from the publisher. Inquiries should be
addressed to ITCourseware, LLC, 7245 South Havana Street, Suite 100, Englewood, CO, 80112.
(303) 302-5280
All brand names, product names, trademarks, and registered trademarks are the property of their respective
owners.
© 2008 ITCourseware, LLC Rev 4.1.1 Page iii
XSLT
Contents
Chapter 1 - Course Introduction ............................................................................................................. 7
Course Objectives ............................................................................................................................ 8
Course Overview ........................................................................................................................... 10
Using the Workbook ...................................................................................................................... 11
Suggested References ..................................................................................................................... 12
Chapter 2 - Introduction to XSLT ......................................................................................................... 15
Stylesheet, Source, and Result ........................................................................................................ 16
XSLT Processors ........................................................................................................................... 18
Processor Implementations ............................................................................................................. 20
XPath Basics .................................................................................................................................. 22
xsl:stylesheet ................................................................................................................................... 24
xsl:template ..................................................................................................................................... 26
xsl:value-of ..................................................................................................................................... 28
xsl:apply-templates ......................................................................................................................... 30
xsl:output ........................................................................................................................................ 32
Labs ............................................................................................................................................... 34
Chapter 3 - XPath Nodetypes .............................................................................................................. 37
XPath Expressions .......................................................................................................................... 38
XPath Context ................................................................................................................................ 40
XPath Location Steps ..................................................................................................................... 42
Element and Root Nodes ................................................................................................................ 44
Text and Attribute Nodes ................................................................................................................ 46
Comment and Processing Instruction Nodes .................................................................................... 48
Namespace Nodes ......................................................................................................................... 50
Wildcards ....................................................................................................................................... 52
Whitespace .................................................................................................................................... 54
Default Template Rules ................................................................................................................... 56
Labs ............................................................................................................................................... 58
Page iv Rev 4.1.1 © 2008 ITCourseware, LLC
XSLT
Chapter 4 - XPath Axes and Predicates ................................................................................................ 61
Location Paths and Location Steps ................................................................................................. 62
Peer Axis Types .............................................................................................................................. 64
More Peer Axis Types .................................................................................................................... 66
Descendant Axis Types ................................................................................................................... 68
Ancestor Axis Types ....................................................................................................................... 70
Node Tests ..................................................................................................................................... 72
Predicates ...................................................................................................................................... 74
Functions ........................................................................................................................................ 76
Labs ............................................................................................................................................... 78
Chapter 5 - XSLT Flow Control ........................................................................................................... 81
xsl:if ................................................................................................................................................ 82
xsl:choose ....................................................................................................................................... 84
xsl:for-each ..................................................................................................................................... 86
xsl:sort ............................................................................................................................................ 88
Named Templates ........................................................................................................................... 90
Mode ............................................................................................................................................. 92
Labs ............................................................................................................................................... 94
Chapter 6 - Generating Output with XSLT ............................................................................................ 97
Output Methods ............................................................................................................................. 98
HTML Output .............................................................................................................................. 100
Plain Text Output .......................................................................................................................... 102
XML Output ................................................................................................................................ 104
xsl:element and xsl:attribute ........................................................................................................... 106
Attribute Value Templates ............................................................................................................. 108
xsl:attribute-set ............................................................................................................................. 110
Text, Processing-Instructions, and Comments ................................................................................ 112
Working with Namespaces ........................................................................................................... 114
Labs ............................................................................................................................................. 116
Chapter 7 - Using XPath and XSLT Functions .................................................................................... 119
XPath Datatypes and Functions .................................................................................................... 120
Node Test Functions ..................................................................................................................... 122
Node Set Functions ...................................................................................................................... 124
Boolean Functions ........................................................................................................................ 126
String Functions ............................................................................................................................ 128
© 2008 ITCourseware, LLC Rev 4.1.1 Page v
XSLT
Number Functions ........................................................................................................................ 130
id() Function ................................................................................................................................. 132
XSLT Functions ........................................................................................................................... 134
The document() Function .............................................................................................................. 136
xsl:key and the key() Function ....................................................................................................... 138
Labs ............................................................................................................................................. 140
Chapter 8 - Advanced XSLT .............................................................................................................. 143
Copying Elements ......................................................................................................................... 144
Numbering ................................................................................................................................... 146
Variables ...................................................................................................................................... 148
Parameters ................................................................................................................................... 150
Using Other Stylesheets ................................................................................................................ 152
Apply-imports .............................................................................................................................. 154
Template Rule Conflicts ................................................................................................................ 156
Extensions .................................................................................................................................... 158
Labs ............................................................................................................................................. 160
Appendix A - XSLT and XPath 2.0 New Features .............................................................................. 163
XSLT 2.0 Grouping Elements and Functions ................................................................................. 164
User-Defined XSLT Functions ...................................................................................................... 166
Multiple Output and XHTML Documents ...................................................................................... 168
Temporary Trees .......................................................................................................................... 170
Sequences .................................................................................................................................... 172
Types ........................................................................................................................................... 174
Stylesheets That Are Schema-Aware ............................................................................................. 176
Character Mapping ....................................................................................................................... 178
Regular Expressions ...................................................................................................................... 180
Labs ............................................................................................................................................. 182
Solutions ............................................................................................................................................ 185
Index .................................................................................................................................................. 223
Page vi Rev 4.1.1 © 2008 ITCourseware, LLC
XSLT
Chapter 1 Course Introduction
© 2008 ITCourseware, LLC Rev 4.1.1 Page 7
Chapter 1 - Course Introduction
XSLT
Page 8 Rev 4.1.1 © 2008 ITCourseware, LLC
� Write XSLT stylesheets that produce HTML, XML, and text.
� Identify XML elements using XPath.
� Use XPath functions and predicates.
� Call specifically named templates.
� Sort data and use modes.
� Use XPath string functions to manipulate string values.
� Create and format numbers in the result document.
� Use variables and parameters within a stylesheet.
� Import templates from other XSLT stylesheets.
� Define precedence of XSLT templates.
Course Objectives
Chapter 1 Course Introduction
© 2008 ITCourseware, LLC Rev 4.1.1 Page 9
XSLT
Page 10 Rev 4.1.1 © 2008 ITCourseware, LLC
� Audience: Developers who wish to transform XML documents into other XML
documents, HTML, or text using XSLT.
� Prerequisites: Experience using XML.
� Classroom Environment:
� Workstation per student with a text editor and an XSLT processor.
Course Overview
Chapter 1 Course Introduction
© 2008 ITCourseware, LLC Rev 4.1.1 Page 11
Chapter 2 Servlet Basics
© 2002 ITCourseware, LLC Rev 2.0.0 Page 17
Add an init() method to your Today servlet that initializes a bornOn date, then print the bornOn date
along with the current date:
Today.java
...
public class Today extends GenericServlet {
private Date bornOn;
public void service(ServletRequest request,
ServletResponse response) throws ServletException, IOException
{
...
// Write the document
out.println("This servlet was born on " + bornOn.toString());
out.println("It is now " + today.toString());
}
public void init() {
bornOn = new Date();
}
}
Hands On:
The init() method is
called when the servlet is
loaded into the container.
This workbook design is based on a page-pair, consisting of a Topic page and a Support page. When you
lay the workbook open flat, the Topic page is on the left and the Support page is on the right. The Topic
page contains the points to be discussed in class. The Support page has code examples, diagrams, screen
shots and additional information. Hands On sections provide opportunities for practical application of key
concepts. Try It and Investigate sections help direct individual discovery.
In addition, there is an index for quick look-up. Printed lab solutions are in the back of the book as well as
on-line if you need a little help.
Java Servlets
Page 16 Rev 2.0.0 © 2002 ITCourseware, LLC
� The servlet container controls the life cycle of the servlet.
� When the first request is received, the container loads the servlet class
and calls the init() method.
� For every request, the container uses a separate thread to call
the service() method.
� When the servlet is unloaded, the container calls the destroy()
method.
� As with Java’s finalize() method, don’t count on this being
called.
� Override one of the init() methods for one-time initializations, instead of
using a constructor.
� The simplest form takes no parameters.
public void init() {...}
� If you need to know container-specific configuration information, use
the other version.
public void init(ServletConfig config) {...
� Whenever you use the ServletConfig approach, always call the
superclass method, which performs additional initializations.
super.init(config);
The Servlet Life Cycle
The Topic page provides
the main topics for
classroom discussion.
The Support page has
additional information,
examples and suggestions.
Code examples are in a
fixed font and shaded. The
on-line file name is listed
above the shaded area.
Screen shots show
examples of what you
should see in class.
Topics are organized into
first (�), second (�) and
third (�) level points.
Pages are numbered
sequentially throughout
the book, making lookup
easy.
Callout boxes point out
important parts of the
example code.
Using the Workbook
XSLT
Page 12 Rev 4.1.1 © 2008 ITCourseware, LLC
DuCharme, Bob. 2001. XSLT Quickly. Manning Publications Co., Greenwich, CT. ISBN 1930110111.
Harold, Elliotte Rusty and W. Scott Means. 2004. XML in a Nutshell, 3rd Edition. O'Reilly &
Associates, Sebastopol, CA. ISBN 0596007647.
Kay, Michael. 2008. XSLT 2.0 and XPath 2.0 Programmer's Reference (Programmer to
Programmer). Wrox Press, Chicago, IL. ISBN 0470192747.
St. Laurent, Simon and Michael Fitzgerald. 2005. XML Pocket Reference, 3rd Edition. O'Reilly &
Associates, Sebastopol, CA. ISBN 0596100507.
Tidwell, Doug. 2008. XSLT, 2nd Edition. O'Reilly & Associates, Sebastopol, CA. ISBN 0596527217.
www.w3.org/Style/XSL/
Suggested References
Chapter 1 Course Introduction
© 2008 ITCourseware, LLC Rev 4.1.1 Page 13
XSLT
Page 14 Rev 4.1.1 © 2008 ITCourseware, LLC
Chapter 2 Introduction to XSLT
© 2008 ITCourseware, LLC Rev 4.1.1 Page 15
Chapter 2 - Introduction to XSLT
Objectives
� Use XSLT to transform an XML document
into a different document.
� Describe the relationship between a
processor, stylesheet, source document,
and result document.
� Define a transformation rule that will
apply to a series of matching elements.
� Extract data from a source document and
insert it into a result document.
XSLT
Page 16 Rev 4.1.1 © 2008 ITCourseware, LLC
� Extensible Stylesheet Language Transformation (XSLT) is about transforming
XML documents into something else.
� The starting XML document is the source document.
� The "something else" is the result document.
� An XSLT stylesheet is an XML document that spells out the rules of a
particular transformation.
� An XSLT processor parses the source document and creates a source tree in
memory.
� The rules of the stylesheet are applied to create a result tree, which is converted
to the result doument.
� This can be another XML document, an HTML document, or plain text.
� XSL-FO is a particular XML schema that can be leveraged to
produce more complex types of documents, like PDF or RTF.
� Being XML, the stylesheet must be well-formed.
� If the result document is to be HTML, the stylesheet must include well-
formed HTML.
� Stylesheet elements must be associated with the namespace http://www.w3.org/
1999/XSL/Transform.
Stylesheet, Source, and Result
Chapter 2 Introduction to XSLT
© 2008 ITCourseware, LLC Rev 4.1.1 Page 17
XML source
document
XSLT
stylesheet
Processor
source tree result tree
result
document
The term "XSL" is sometimes used to refer to the process diagrammed here, where an XSLT stylesheet is
used to transform an XML source into a different result document.
However, the term "XSL" is also used to describe a more complete process, as the W3C originally
conceived of it. Formatting objects (XSL-FO) is a platform- and media-independent formatting language
described in the original XSL specification. XSL-FO is first used to generate an XML result document from
XSLT. Then, an FO processor is applied to the formatting objects to create a specific binary representation,
perhaps PDF or RTF.
So, while XSLT and XSL-FO are clearly identifiable processes, XSL sometimes refers to XSLT alone and
other times refers to the combination of XSLT and XSL-FO.
XSLT
Page 18 Rev 4.1.1 © 2008 ITCourseware, LLC
� An XSLT processor is responsible for applying an XSLT stylesheet to a source
XML document and producing a result document.
� Processors can be applied in several different ways.
� A processor can be applied as a standalone application.
� These are often started from a command prompt.
� A processor can be applied via API calls from a programming language.
� Transformation APIs exist for a variety of languages.
� A simple standalone program might be developed to stream the
result document to a console or file.
� The transformation could be made by a web or application server
component, in which case the result would typically be streamed to
a browser-based client.
� A processor can be applied directly within a web browser.
� The browser downloads the XML source, applies the stylesheet,
and displays the result.
� Browsers recognize the xml-stylesheet processing instruction, and
use it to associate the XML file with a particular stylesheet.
<?xml-stylesheet type="text/xsl" href="example.xsl"?>
XSLT Processors
Chapter 2 Introduction to XSLT
© 2008 ITCourseware, LLC Rev 4.1.1 Page 19
There are two ways to apply XSLT within a web context:
1. The web browser invokes its XSLT processor after it acquires the source and stylesheet.
2. The web server invokes an XSLT processor and streams the result back to the browser.
Browser Processor
WebServer
XML Source
XSLT
HTML Result
Browser Web Server Processor XML
Source
XSLT
HTML Result
XSLT
Page 20 Rev 4.1.1 © 2008 ITCourseware, LLC
Processor Implementations
� The Apache Xalan processor is an open-source implementation that can be used
from a command prompt or via API calls.
� Apache Xalan has implementations for Java and C++.
� Microsoft's MSXML is integrated into Internet Explorer versions 5.5 and later.
� Microsoft provides an ISAPI filter, so that server-side transformations
can be easily performed from IIS.
� MSXML can also be accessed as a COM object from VB, VC++, or C#
programs.
� Michael Kay's SAXON is a command-line processor that includes Java and
.NET APIs.
� Ginger Alliance's open-source Sablotron processor includes a command-line
interface and a C API, as well as wrapper APIs for Perl, PHP, Python, Ruby,
and others.
� The Apache Cocoon project is an XML publishing framework that can be run
within a Web server.
� It can also be used through a command-line interface.
� Cocoon utilizes transformations of XML data to separate the concerns of
style and logic as they pertain to web content.
� AltovaXML provides the same engines, including an XSLT processor, that drive
the popular XMLSpy and other Altova products.
� It provides command-line, COM, .NET, and Java interfaces.
Chapter 2 Introduction to XSLT
© 2008 ITCourseware, LLC Rev 4.1.1 Page 21
Most XSLT processors are available over the World Wide Web.
Apache Xalan is available at http://xml.apache.org/xalan-j/index.html
Apache Cocoon is available at http://xml.apache.org/cocoon/
Michael Kay's SAXON is available at http://saxon.sourceforge.net/
Ginger Alliance's Sablotron is available at http://www.gingerall.org/sablotron.html
AltovaXML is available at http://www.altova.com/altovaxml.html
XSLT
Page 22 Rev 4.1.1 © 2008 ITCourseware, LLC
XPath Basics
� Many XSLT elements use XPath to specify the pattern for matching or selecting
a node or group of nodes.
� XPath views an XML document as a tree with different node types, and uses
different constructs to select them.
� Use / to identify the root node, which is the root of the source tree, not
the root element.
� Use the element name to identify an element.
� Identify an attribute with @attributeName.
� Select all elements at the specified point in the tree with * and all attributes
with @*.
� XPath patterns can include navigation of the document's tree.
� Pattern matches start from the current node location or context.
� A leading slash (/) forces the search from the root node and other slashes
act as level separators.
� . matches the current node and .. matches the parent node.
� | acts as an "or," allowing you to select nodes matching any of the
specified patterns.
� A predicate allows conditions inside of a trailing [ ] to further limit the collection
of nodes matched by the expression.
Chapter 2 Introduction to XSLT
© 2008 ITCourseware, LLC Rev 4.1.1 Page 23
If the current (context) node is garage, the following XPath expressions would retrieve all of the car make
elements in the garage:
/garage/car/make or car/make or ./car/make
One expression for accessing all car makes for the year 2007 would be:
/garage/car/make[../year='2007']
root
node
processing
instruction
garage
element
car
element
miles
attribute
make
element
text
node
model
element
year
element
text
node
text
nodecar
element
...
XSLT
Page 24 Rev 4.1.1 © 2008 ITCourseware, LLC
� The root element of a stylesheet is xsl:stylesheet.
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
� Include the namespace declaration.
� xsl is the namespace prefix by convention only.
� A version attribute is required.
� Many elements are allowed as children of xsl:stylesheet.
� These are called top-level elements and can include:
� import and include elements to use other stylesheets
� An output element to specify the type of output document
� template elements
� Other than having any import children occur first, ordering of top-level
elements is arbitrary.
� The XSLT namespace offers the alternative root element xsl:transform.
� There is no difference between xsl:stylesheet and xsl:transform.
xsl:stylesheet
Chapter 2 Introduction to XSLT
© 2008 ITCourseware, LLC Rev 4.1.1 Page 25
This xml-stylesheet
processing instruction tells the
browser to run an XSLT process.
In your chapter directory, you will find garage.xml and garage.xsl. Over the course of the next few pages,
you will edit garage.xsl to transform garage.xml into HTML.
garage.xml<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="garage1.xsl"?>
<garage>
<car miles="0">
<make>Porsche</make>
<model>911</model>
<year>2001</year>
</car>
<car miles="50">
<make>VW</make>
<model>Beetle</model>
<year>1974</year>
</car>
<van miles="30000">
<make>Ford</make>
<model>E350</model>
<year>2000</year>
</van>
</garage>
Hands On:
Add a stylesheet element to your garage.xsl document:
<?xml version="1.0"?>
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<html><body><div align="center">
<h1>Stuff in my Garage</h1>
<table border="1">
<tr><td>YEAR</td><td>MAKE</td><td>MODEL</td><td>MILES</td></tr>
</table>
</div></body></html>
</xsl:stylesheet>
Note:
You will not be able to use your stylesheet at this time. Can you guess why?
XSLT
Page 26 Rev 4.1.1 © 2008 ITCourseware, LLC
� A template is an XSLT element that defines a translation rule.
� Many templates can exist within the same document.
� Define a template with the xsl:template element.
<xsl:template match="pattern">
content
</xsl:template>
� Use the match attribute to define an XPath expression that indicates the
nodes to which this template could apply.
� Non-XSLT element and text content are moved into the result tree.
� XSLT child element content is processed according to the element rules.
� Most stylesheets have at least one xsl:template element: the root template.
� The value of the match attribute is /, which is the XPath syntax for the
root node.
<xsl:template match="/">
xsl:template
Chapter 2 Introduction to XSLT
© 2008 ITCourseware, LLC Rev 4.1.1 Page 27
Hands On:
Add the root template to your garage.xsl document. Then process garage.xml by opening it in a browser.
Note that although we are transforming the garage XML data, none of the actual XML data is included in
the output at this point.
<?xml version="1.0"?>
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html><body><div align="center">
<h1>Stuff in my Garage</h1>
<table border="1">
<tr>
<td>YEAR</td><td>MAKE</td><td>MODEL</td><td>MILES</td>
</tr>
</table>
</div></body></html>
</xsl:template>
</xsl:stylesheet>
XSLT
Page 28 Rev 4.1.1 © 2008 ITCourseware, LLC
� Use xsl:value-of to move XML source text to the result tree.
� This will be a subelement of xsl:template.
� The select attribute specifies an XPath pattern to the element of interest.
<xsl:value-of select="element-pattern"/>
� The value of the select attribute is an XPath expression starting
from the perspective of the template that is being processed.
� xsl:value-of processing executes on only the first node of a multi-
valued select return.
� If the selected element contains character data, that string is returned.
� If the selected element contains additional subelements, a concatenation
of all descendant character data is produced.
� Depending on the nature of your XML, you might need to employ
the XPath text() function to navigate directly to an element's text
node.
<xsl:value-of select="element-pattern/text()"/>
� Retrieve attribute values by prepending the @ character to the attribute
name within the pattern.
<xsl:value-of select="attribute-path/@attribute-name"/>
xsl:value-of
Chapter 2 Introduction to XSLT
© 2008 ITCourseware, LLC Rev 4.1.1 Page 29
Hands On:
Add multiple xsl:value-of elements to garage.xsl in order to extract the text of the year, make, model,
and miles associated with the cars of your garage. Do this within the root template. Because the context of
the root template is the root node, the XPath expressions will have to include the navigation through the
garage and car elements.
<?xml version="1.0"?>
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html><body><div align="center">
<h1>Stuff in my Garage</h1>
<table border="1">
<tr>
<td>YEAR</td><td>MAKE</td><td>MODEL</td><td>MILES</td>
</tr>
<tr>
<td><xsl:value-of select="garage/car/year"/></td>
<td><xsl:value-of select="garage/car/make"/></td>
<td><xsl:value-of select="garage/car/model"/></td>
<td><xsl:value-of select="garage/car/@miles"/></td>
</tr>
</table>
</div></body></html>
</xsl:template>
</xsl:stylesheet>
Refresh your browser to run the transformation and note the result. You should observe that with the XSLT
rules we have available at this point, we are only extracting the data associated with the first car of the
garage. Clearly, we will want to find a way to work with all of the vehicles in the garage.
XSLT
Page 30 Rev 4.1.1 © 2008 ITCourseware, LLC
� To process a template other than the root template, use xsl:apply-templates.
� Use xsl:apply-templates from within an xsl:template.
� Use the select attribute to define an XPath expression which indicates the nodes
that need processing through another template.
<xsl:apply-templates select="myPattern"/>
� If the select attribute is omitted, it is equivalent to select="*".
� When the XSLT processor identifies an xsl:apply-templates element, it applies
any templates that match the select attribute.
<xsl:template match="matchingPattern">
actions
</xsl:template>
� When there are multiple nodes that match the selection in the source tree,
the processor repeats the template for each node.
� The xsl:apply-templates facility provides a motivation for having multiple
templates in your stylesheet.
� Template order is arbitrary.
� Each template will have its own default node context from which further
XPath evaluations begin.
xsl:apply-templates
Chapter 2 Introduction to XSLT
© 2008 ITCourseware, LLC Rev 4.1.1 Page 31
Hands On:
Edit garage.xsl to create a new template that would handle each car or van that is a subelement of the
garage. This template should extract the values of the car or van into a row of an HTML table. Further edit
the same file to update the root template. The root template should start the table, including the header row,
and then apply the new template for each car and van.
<?xml version="1.0"?>
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html><body><div align="center">
<h1>Stuff in my Garage</h1>
<table border="1">
<tr>
<td>YEAR</td><td>MAKE</td><td>MODEL</td><td>MILES</td>
</tr>
<xsl:apply-templates select="garage/*"/>
</table>
</div></body></html>
</xsl:template>
<xsl:template match="car|van">
<tr>
<td><xsl:value-of select="year"/></td>
<td><xsl:value-of select="make"/></td>
<td><xsl:value-of select="model"/></td>
<td><xsl:value-of select="@miles"/></td>
</tr>
</xsl:template>
</xsl:stylesheet>
Run the transformation again by refreshing your browser and note that all of the garaged cars and vans are
included as part of the output.
XSLT
Page 32 Rev 4.1.1 © 2008 ITCourseware, LLC
� Standard XSLT processors can create XML, HTML, or text output.
� Specify the output type with the xsl:output element and the respective value on
the method attribute.
<xsl:output method="xml"/>
� xsl:output needs to be a top-level XSLT element.
� Without an xsl:output element, the default document type will be XML.
� However, if the result document begins with html, the default document
type will be HTML.
� When creating an HTML document, the stylesheet needs to use XHTML.
� XHTML is well-formed, keeping the stylesheet well-formed.
� The resulting document, however, will be HTML, not XHTML.
� If you want the resulting document to be XHTML, then set the
xsl:output element attribute value to "xml".
xsl:output
Chapter 2 Introduction to XSLT
© 2008 ITCourseware, LLC Rev 4.1.1 Page 33
Hands On:Edit garage.xsl to include an output element indicating the desired output type. Why has the result of your
transformation not changed?
<?xml version="1.0"?>
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:template match="/">
...
</xsl:template>
</xsl:stylesheet>
Try It:Sometimes you will need to produce text as output. In this case, a browser is not the most appropriate
XSLT processor. Use the AltovaXML utility to process the garage.xml against garage_report.xsl to
provide a text report of the garage contents. Your instructor will explain the exact syntax for the AltovaXML
processor. For this example, it should be:
AltovaXML /xslt2 garage_report.xsl /in garage.xml
garage_report.xsl<?xml version="1.0"?>
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="/">
Stuff in my Garage
<xsl:apply-templates select="garage/*"/>
</xsl:template>
<xsl:template match="car|van">
YEAR:<xsl:value-of select="year"/>
MAKE:<xsl:value-of select="make"/>
MODEL:<xsl:value-of select="model"/>
MILES:<xsl:value-of select="@miles"/>
<xsl:text>
</xsl:text>
</xsl:template>
</xsl:stylesheet>
XSLT
Page 34 Rev 4.1.1 © 2008 ITCourseware, LLC
� Transform menu.xml into an HTML document that presents a grocery list of ingredients.
(Solutions: grocery.xsl, menu1.xml)
� Transform menu.xml into an HTML document that presents a recipe list in tables.
(Solutions: recipe.xsl, menu2.xml)
� Transform menu.xml into an HTML document that presents a menu for our customers.
(Solutions: menu.xsl, menu3.xml)
Labs
Chapter 2 Introduction to XSLT
© 2008 ITCourseware, LLC Rev 4.1.1 Page 35
menu.dtd<!ELEMENT menu (recipe*)>
<!ELEMENT recipe (type, title, price, cost, description,
ingredient+, instruction)>
<!ELEMENT type (#PCDATA)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT price (#PCDATA)>
<!ELEMENT cost (#PCDATA)>
<!ELEMENT description (#PCDATA)>
<!ELEMENT ingredient (measurement, item)>
<!ELEMENT measurement (#PCDATA)>
<!ELEMENT item (#PCDATA)>
<!ELEMENT instruction (#PCDATA)>
Chapter 5 XSLT Flow Control
© 2008 ITCourseware, LLC Rev 4.1.1 Page 81
Chapter 5 - XSLT Flow Control
Objectives
� Conditionally process source nodes.
� Apply rules to all nodes within a node list.
� Sort data within the result tree.
� Call a specifically named template.
� Invoke a template based on mode.
XSLT
Page 82 Rev 4.1.1 © 2008 ITCourseware, LLC
� You can add conditional expressions to your stylesheet with the xsl:if element.
� An xsl:if element includes a test attribute.
� If the test attribute value evaluates to true, the body content of the xsl:if
element is added to the result tree.
� The test value can be an XSLT expression that uses functions, node tests, and
operators.
<xsl:if test="count(mission) > 1">
� When you compare with < or >, it is safer to use the entity references < or
>.
� Some processors will handle > correctly, but not <.
� There is no corresponding else element for the xsl:if element.
xsl:if
Chapter 5 XSLT Flow Control
© 2008 ITCourseware, LLC Rev 4.1.1 Page 83
Select the element that has an
ID type attribute with a value
equal to the value of @iref.
In these examples, you will be working with an XML representation of a shopping cart.
shoppingcart.xml<shoppingcart>
...
<items>
<lineItem iref="sgc9233">
<quantity>3</quantity>
<lineTotal>13.50</lineTotal>
</lineItem>
...
<total>27.90</total>
</items>
<item id="sgc9233">
<upc>3402349233</upc>
<name>Marigold, 6-pk</name>
<price>4.50</price>
</item>
...
</shoppingcart>
The stylesheets that follow make use of the id() function which allows a stylesheet to link to different parts ofthe XML document. The function takes an IDREF or IDREFS attribute and returns the element(s) with the
associated matching ID attribute. A DTD identifies the ID and IDREF/IDREFS attributes.
checkout1.xsl<?xml version="1.0"?>
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
...
<xsl:template match="lineItem" mode="summary">
<tr><td><xsl:value-of select="id(@iref)/name"/></td>
<td align="right">
<xsl:if test="number(quantity) >= 5">
<xsl:value-of select="number(lineTotal)*0.8"/></xsl:if>
<xsl:if test="number(quantity) < 5">
<xsl:value-of select="lineTotal"/></xsl:if>
</td></tr>
</xsl:template>
...
</xsl:stylesheet>
Try It:Add the stylesheet processing instruction to shoppingcart.xml to apply the checkout1.xsl stylesheet. Load
shoppingcart.xml in your browser. The result illustrates how the if construct is utilized to apply a 20%
discount on the purchase of five or more of a particular line item.
XSLT
Page 84 Rev 4.1.1 © 2008 ITCourseware, LLC
� The xsl:choose element selects from multiple conditions.
� This is similar to a switch in C-based languages or a select in VB.
� The xsl:choose element contains one or more xsl:when elements.
� The xsl:when element has a test attribute, just like the xsl:if element.
� If the test expression evaluates to true, the children of the xsl:when
element are placed in the result.
� Unlike C cases, xsl:when does not "fall through."
� An xsl:choose can optionally include an xsl:otherwise element, which specifies
the default condition.
� You can also use an xsl:choose as an if-then-else construct.
xsl:choose
Chapter 5 XSLT Flow Control
© 2008 ITCourseware, LLC Rev 4.1.1 Page 85
Note that the builit-in
entity reference is
necessary for the
comparison.
With xsl:if it was kind of awkward to have an else condition. In fact, we just had to make another xsl:if.
With xsl:choose we do not have to repeat the condition.
checkout2.xsl...
<xsl:template match="lineItem" mode="summary">
<tr><td><xsl:value-of select="id(@iref)/name"/></td>
<td align="right">
<xsl:choose>
<xsl:when test="number(quantity) >= 5">
<xsl:value-of select="number(lineTotal)*0.8"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="lineTotal"/>
</xsl:otherwise>
</xsl:choose>
</td></tr>
</xsl:template>
...
Try It:Update the stylesheet processing instruction in shoppingcart.xml to apply the checkout2.xsl stylesheet.
Load the file into your browser to view the transformation. Note how the xsl:choose construct provides a
similar result to the previous example with the xsl:if construct.
XSLT
Page 86 Rev 4.1.1 © 2008 ITCourseware, LLC
� XSLT does not include a traditional loop construct, such as a for loop or a
while loop.
� In programming languages, for loops are often used to iterate through an array
or a collection.
� In Java, this might look like:
for (int i=0; i<data.length; i++)
� The xsl:for-each element iterates through a list.
� You do not have to create or manage an iterator.
� Specify the list of nodes with the select attribute.
� The child nodes of the xsl:for-each will be applied to each member of the
selected node list.
� This works similar to combined xsl:apply-templates and xsl:template
elements.
� xsl:for-each resets the context node on each iteration.
xsl:for-each
Chapter 5 XSLT Flow Control
© 2008 ITCourseware, LLC Rev 4.1.1 Page 87
Process each lineItem
node according to the
rules within each of the
xsl:for-each elements.
checkout3.xsl...
Shopping Cart Summary:
...
<xsl:for-each select="items/lineItem">
<tr><td><xsl:value-of select="id(@iref)/name"/></td>
<td align="right">
<xsl:choose>
<xsl:when test="number(quantity) >= 5">
<xsl:value-of select="number(lineTotal)*0.8"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="lineTotal"/>
</xsl:otherwise>
</xsl:choose>
</td></tr>
</xsl:for-each>
...
Shopping Cart Detail:
...
<xsl:for-each select="items/lineItem">
<tr><td><xsl:value-of select="id(@iref)/name"/></td>
<td><xsl:value-of select="id(@iref)/upc"/></td>
<td align="right">
<xsl:value-of select="id(@iref)/price"/></td>
<td align="right">
<xsl:value-of select="quantity"/></td>
<td align="right">
<xsl:value-of select="lineTotal"/></td></tr>
</xsl:for-each>
...
Try It:Update the stylesheet processing instruction in shoppingcart.xml to apply the checkout3.xsl stylesheet.
Load shoppingcart.xml in your browser and compare the result with your previous transformation. Review
the changes in checkout3, where the for-each construct is used in two places in lieu of the
apply-templates / template elements. Note that the use of for-each produces the same transformation
result.
XSLT
Page 88 Rev 4.1.1 © 2008 ITCourseware, LLC
� The xsl:sort element specifies the order in which a group of nodes will be
processed.
� xsl:sort always appears as the first child of either xsl:apply-templates or
xsl:for-each.
� The sorting is done alphabetically, as specified by the lang attribute.
� You can set the order attribute to either ascending or descending.
� You can specify whether uppercase or lowercase letters come first with
the case-order attribute.
� The values are upper-first or lower-first.
� You can specify whether to sort alphabetically or numerically with the
data-type attribute.
� The values are text or number.
� xsl:sort includes a select attribute, which specifies the nodes to be used in
sorting.
� Use "." to specify the current nodes chosen from the parent element.
� If you have multiple xsl:sort elements, the first is the primary sort, the second is
the secondary sort, and so on.
xsl:sort
Chapter 5 XSLT Flow Control
© 2008 ITCourseware, LLC Rev 4.1.1 Page 89
Sort the nodes for
xsl:for-each processing.
Sort the nodes to be
processed by a
matching template.
checkout4.xsl...
<xsl:for-each select="items/lineItem">
<xsl:sort select="lineTotal" data-type="number"/>
<tr><td><xsl:value-of select="id(@iref)/name"/></td>
<td align="right">
<xsl:choose>
<xsl:when test="number(quantity) >= 5">
<xsl:value-of select="number(lineTotal)*0.8"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="lineTotal"/>
</xsl:otherwise>
</xsl:choose>
</td></tr>
</xsl:for-each>
...
<xsl:apply-templates select="items/lineItem">
<xsl:sort select="id(@iref)/price" data-type="number"/>
</xsl:apply-templates>
...
Try It:Update the stylesheet processing instruction in shoppingcart.xml to apply the checkout4.xsl stylesheet and
reload the document. Verify the results with what you would expect from the newly inserted sort elements.
Why is data-type="number" needed as attributes of these sort elements?
XSLT
Page 90 Rev 4.1.1 © 2008 ITCourseware, LLC
� It can be useful to invoke a template without having to match an XPath
expression.
� Name a template with the name attribute of the xsl:template element.
<xsl:template name="header">
� Do not include a match attribute.
� Invoke the template with the xsl:call-template element.
<xsl:call-template name="header"/>
� Named templates can be used to easily add common elements, such as headers
or footers to your result.
� Use named templates for repetitive information that you only want to
update in one place.
� When a named template is invoked, the context node is not changed.
� A named template can, but often does not, make use of the context
node.
� You can leverage two other related reuse mechanisms: the xsl:include and
the xsl:import elements.
Named Templates
Chapter 5 XSLT Flow Control
© 2008 ITCourseware, LLC Rev 4.1.1 Page 91
Define the template
named header.
checkout5.xsl<?xml version="1.0"?>
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:template name="header">
<head><title>Sam's Garden Center</title></head>
</xsl:template>
<xsl:template name="mastHead">
<center><h1><font color="green">Sam's Garden Center</font></h1></center>
<center><h2>checkout</h2></center>
<hr/>
</xsl:template>
<xsl:template match="shoppingcart">
<html>
<xsl:call-template name="header"/>
<body>
<xsl:call-template name="mastHead"/>
Shopping Cart Summary:
<table width="60%" align="center" border="1">
...
</xsl:stylesheet>
Try It:Update the stylesheet processing instruction in shoppingcart.xml to apply the checkout5.xsl stylesheet.
Apply the transformation through the browser. Note how call-template elements cause the named
templates to be inserted into the result document.
Call the template
named header.
XSLT
Page 92 Rev 4.1.1 © 2008 ITCourseware, LLC
� It is sometimes necessary to create different templates with the same match
expression.
� This enables you to process the same set of nodes in different ways
within the same transformation.
� An example might be the requirement to show an order's line items
in detail and as cost summaries in different parts of the same
display.
� Use the template mode to specify which template you want to use at what time.
� Set the mode with the mode attribute in the xsl:template element.
<xsl:template match="lineItem" mode="summary">
� Invoke the template with the mode attribute in the xsl:apply-templates element.
<xsl:apply-templates select="items/lineItem" mode="summary"/>
� If a template does not exist in a certain mode, then the default template
will be used.
Mode
Chapter 5 XSLT Flow Control
© 2008 ITCourseware, LLC Rev 4.1.1 Page 93
Send lineItem nodes to a matching template
that handles the mode="summary" condition.
checkout6.xsl
<?xml version="1.0"?>
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:template name="header">
...
Shopping Cart Summary:
<table width="60%" align="center" border="1">
<tr><th width="75%">Item</th><th width="25%">amount</th></tr>
<xsl:apply-templates select="items/lineItem" mode="summary">
<xsl:sort select="lineTotal" data-type="number"/>
</xsl:apply-templates>
...
Shopping Cart Detail:
<table width="60%" align="center" border="1">
...
<xsl:apply-templates select="items/lineItem" mode="detail">
<xsl:sort select="id(@iref)/price" data-type="number"/>
</xsl:apply-templates>
</table>
...
</xsl:template>
<xsl:template match="lineItem" mode="summary">
<tr><td><xsl:value-of select="id(@iref)/name"/></td>
<td align="right">
<xsl:choose>
<xsl:when test="number(quantity) >= 5">
<xsl:value-of select="number(lineTotal)*0.8"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="lineTotal"/>
</xsl:otherwise>
</xsl:choose>
</td></tr>
</xsl:template>
<xsl:template match="lineItem" mode="detail">
<tr><td><xsl:value-of select="id(@iref)/name"/></td>
<td><xsl:value-of select="id(@iref)/upc"/></td>
<td align="right"><xsl:value-of select="id(@iref)/price"/></td>
<td align="right"><xsl:value-of select="quantity"/></td>
<td align="right"><xsl:value-of select="lineTotal"/></td></tr>
</xsl:template>
...
Try It:Update the stylesheet processing instruction in shoppingcart.xml to apply the checkout6.xsl stylesheet. Loadshoppingcart.xml in your browser. Review the changes in checkout6.xsl to see that the mode attribute hasbeen introduced to the template elements. Note how a mode attribute is used with the apply-templates
elements to specify a particular template.
A template that matches lineItem nodes
under the mode="summary" condition.
XSLT
Page 94 Rev 4.1.1 © 2008 ITCourseware, LLC
� Write a stylesheet that builds an HTML document with a table that lists each of the Apollo missions
and the astronauts that flew on them. Test your code using apollo2.xml.
(Solution: apollo.xsl)
� Use named templates to add a head section and a masthead to your previous Apollo HTML
document. Test your code using apollo2.xml.
(Solution: apollo2.xsl)
� Write a stylesheet that creates an HTML display of all Extravehicular Activities (EVAs). For each
EVA, include the mission name, the initials of all astronauts involved, and whether the EVA was on
the lunar surface or in space. Test your code using apollo2.xml.
(Solution: evas.xsl)
� (Optional) Update the previous stylesheet to expand the initials of the astronauts to full names. Test
your code using apollo2.xml.
Hint: This will require an additional xsl:for-each tag and the id() function in its select attribute. An
id() function that is passed an attribute of type IDREFS returns the the set of element nodes that
match any of the IDREF values through the element's ID attribute.
(Solution: evas2.xsl)
� Use checkout6.xslt as a starting point and create a stylesheet that formats the summary and detail
tables of the checkout result to alternate the background color of each row between two colors. In
addition, sort both tables according to a common strategy (use each item's name) so that data
across tables can be more easily cross-checked. Test your code using bigshoppingcart.xml.
Hint: Use the position() function and the mod operator to determine whether each row is odd or
even in the table.
(Solution: checkout.xsl)
Labs
Chapter 5 XSLT Flow Control
© 2008 ITCourseware, LLC Rev 4.1.1 Page 95
Chapter 8 Advanced XSLT
© 2008 ITCourseware, LLC Rev 4.1.1 Page 143
Chapter 8 - Advanced XSLT
Objectives
� Create and format numbers in the result
document.
� Create and assign values to variables
within a stylesheet.
� Pass parameters to templates within an
XSLT stylesheet.
� Import templates from other XSLT
stylesheets.
� Define precedence of XSLT templates.
XSLT
Page 144 Rev 4.1.1 © 2008 ITCourseware, LLC
� It may be necessary to copy elements from the source document to the target
document.
� XSLT provides two different methods for copying content.
� The xsl:copy element copies the current node to the output document.
� If the current node is an element, it does not copy attributes or
element content.
� It always implicitly copies the context node.
� It may use attribute sets.
� The xsl:copy-of element is similar to the xsl:value-of element.
� It accepts a target argument using the select attribute.
� It copies an entire result-tree fragment.
� Copying an element also copies attributes, attribute values, and
element content.
Copying Elements
Chapter 8 Advanced XSLT
© 2008 ITCourseware, LLC Rev 4.1.1 Page 145
Particularly for XML-to-XML applications, the ability to copy portions of the source document directly intothe output document is useful. The following XSLT template copies all of the content from the sourcedocument to the target document:
copydoc.xsl<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*|node()">
<xsl:copy><xsl:apply-templates select="@*|node()"/>
</xsl:copy></xsl:template>
</xsl:stylesheet>
Try It:Copy the contents from the source document, apollo.xml, to the result document by transformingapollo.xml with copydoc.xsl.
XSLT
Page 146 Rev 4.1.1 © 2008 ITCourseware, LLC
� The xsl:number element supports generating rich numbering sequences in
output documents.
� The value attribute is an XPath expression that returns the number to be
printed
� Instead of using the value attribute, the number can be calculated
based upon the position of the node.
� The count, from, and level attributes are used when value is
omitted.
� The count attribute is an XPath expression indicating what is to be
counted.
� The from attribute is an XPath expression that indicates the element where
counting begins.
� The level attribute controls how elements are counted.
� The level attribute influences how the other attributes are applied.
� A level of single is the default, and numbers adjacent elements in a simple
list.
� A level of multiple creates a hierarchical numbering scheme (i.e., outline
numbering).
� A level of any counts any preceding matching element (for instance, for
numbering figures or diagrams).
� The final output format can be modified by the format attribute.
� Numerous types of numbering are defined (Arabic, Roman numerals,
lettering, etc.).
Numbering
Chapter 8 Advanced XSLT
© 2008 ITCourseware, LLC Rev 4.1.1 Page 147
Use the following values for the format attribute:
orbits1.xsl<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:template match="apollo">
<html>
<body>
<h1>Apollo Table</h1>
<table border="1">
<tr>
<th>Mission Number</th><th>Orbit Count</th>
</tr>
<xsl:apply-templates select="mission[lunar/orbit/count]"/>
</table>
</body>
</html>
</xsl:template>
<xsl:template match="mission">
<tr>
<td><xsl:value-of select="./text()" /></td>
<td><xsl:number value=".//orbit/count" format="1"/></td><!--<td><xsl:number value=".//orbit/count" format="i"/></td>-->
</tr>
</xsl:template>
</xsl:stylesheet>
Try It:Run orbits1.xsl against the source document, apollo.xml. Notice how the orbit numbers are presenteddepending on the parameter values.
Format Result
"1" 1 2 3 ...
"01" 01 02 03 ...
"a" a b c ...
"A" A B C ...
"I" i ii iii iv ...
"I" I II III IV ...
XSLT
Page 148 Rev 4.1.1 © 2008 ITCourseware, LLC
� You can use variables to hold values that you need to use somewhere else in
your stylesheet.
� If you have a variable named var, access it within XSLT elements with the
$var notation.
� To define a variable, use the xsl:variable element.
� This element can be a top-level element or a child of any other element.
� The parent element of xsl:variable defines the scope of the variable.
� xsl:variable can have two attributes.
� The name attribute defines the name of the variable.
� The select attribute defines the value of the variable.
� Use single quotes around a literal value to prevent the processor
from evaluating it.
� Most processors will recognize a literal value that starts with a
number, even if it is not surrounded by single quotes.
� If you don't specify the select attribute of the xsl:variable, its value will
be an empty string.
� You can reassign values to variables with another xsl:variable element.
� When you reassign values, be careful of the variable's scope.
Variables
Chapter 8 Advanced XSLT
© 2008 ITCourseware, LLC Rev 4.1.1 Page 149
Obtains value of
orbit_limit variable.
orbits2.xsl<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:variable name="orbit_limit" select="20" />
<xsl:template match="apollo">
<html>
<body>
<h1>Apollo Table</h1>
<table border="1">
<tr>
<th>Mission Number</th><th>Orbit Count</th>
</tr>
<xsl:apply-templates
select="mission[.//orbit/count > $orbit_limit]"/></table>
</body>
</html>
</xsl:template>
<xsl:template match="mission">
<tr>
<td><xsl:value-of select="./text()" /></td>
<td><xsl:number value=".//orbit/count" format="1"/></td>
</tr>
</xsl:template>
</xsl:stylesheet>
Try It:Run orbits2.xsl against the source document, apollo.xml. Are there any apollo missions missing from theoutput? Add an additional variable named orbit_limit inside the template that matches apollo and give itthe select value of 5. Perform the transformation again and look for any change in the output. Whichorbit_limit variable has priority?
XSLT
Page 150 Rev 4.1.1 © 2008 ITCourseware, LLC
� You can pass parameters to a stylesheet or a template to provide additional
information.
� Use the xsl:param element to define the parameters that the stylesheet or
template can accept.
� If the xsl:param element is a top-level element, the parameter is global.
� The parameter value can be passed in on the command line.
� If the xsl:param element is a child of a template, the parameter is local to
that template.
� Define the name of the parameter with the name attribute.
� You can specify a default value with the select attribute or defined as a
template within the xsl:param element.
� Enclose literal values within single quotes if you use the select
attribute.
� Set the parameter value with an xsl:with-param element as a child of the
template call.
� The xsl:with-param has the same attributes as the xsl:param element.
� Access the value of the parameter using $param notation, just like a variable.
Parameters
Chapter 8 Advanced XSLT
© 2008 ITCourseware, LLC Rev 4.1.1 Page 151
The parameter
value is "1."
To pass a parameter to a template, include the xsl:with-param element as a child of the element thatinvokes the template:<xsl:call-template name="header"> <xsl:with-param name="background" select="preferences/background"/></xsl:call-template>
or<xsl:apply-templates select="descendant::astronaut"> <xsl:with-param name="title" select="'astronaut'"/></xsl:apply-templates>
Consult your processor's documentation for details on passing a parameter to a stylesheet.
orbits3.xsl<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:variable name="orbit_limit" select="20" />
...
<xsl:apply-templates
select="mission[.//orbit/count > $orbit_limit]">
<xsl:with-param name="numberFormat" select="'1'" /></xsl:apply-templates>
</table>
</body>
</html>
</xsl:template>
<xsl:template match="mission">
<xsl:param name="numberFormat">I</xsl:param><tr>
<td><xsl:value-of select="./text()" /></td>
<td>
<xsl:number value=".//orbit/count" format="{$numberFormat}"/></td>
</tr>
</xsl:template>
</xsl:stylesheet>
Try It:Run orbits3.xsl against the source document, apollo.xml. Modify orbits3.xsl by removing the xsl:with-
param element and run it again. What changed in the output?
The default value is "I."
XSLT
Page 152 Rev 4.1.1 © 2008 ITCourseware, LLC
� XSLT provides two elements for using templates from other stylesheets:
xsl:import and xsl:include.
� The stylesheet that contains the xsl:import or xsl:include element is the
including stylesheet.
� The stylesheet that is being imported or included is the included
stylesheet.
� The xsl:import and xsl:include elements allow you to include templates from
another stylesheet into the including stylesheet.
� Both are empty elements.
� The href attribute specifies the URI of the included stylesheet.
� xsl:import can only appear at the beginning of the including stylesheet.
� All imported templates have a lower priority than the templates in
the including stylesheet.
� xsl:include can be anywhere in the stylesheet, as long as it is a top-level
element.
� The included templates have the same priority as the templates from
the including stylesheet.
Using Other Stylesheets
Chapter 8 Advanced XSLT
© 2008 ITCourseware, LLC Rev 4.1.1 Page 153
external.xsl<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="mission">
<tr bgcolor="cyan">
<td><xsl:value-of select="./text()" /></td>
<td>
<xsl:number value=".//orbit/count" format="A"/>
</td>
</tr>
</xsl:template>
</xsl:stylesheet>
orbits4.xsl<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:import href="external.xsl"/><xsl:output method="html"/>
...
<xsl:template match="mission">
<xsl:param name="numberFormat">I</xsl:param>
<tr>
<td><xsl:value-of select="./text()" /></td>
<td>
<xsl:number value=".//orbit/count" format="{$numberFormat}"/>
</td>
</tr>
</xsl:template>
</xsl:stylesheet>
Try It:Run orbits4.xsl against the source document, apollo.xml. Is the output different? Change the xsl:import toan xsl:include. Is the output different? Move the xsl:include to the bottom of the stylesheet. Is the outputdifferent?
external.xsl contains the
same mission template as
orbits4.xsl.
XSLT
Page 154 Rev 4.1.1 © 2008 ITCourseware, LLC
� When you import another stylesheet using xsl:import, the templates in the other
stylesheet have a lower priority than those in the primary stylesheet.
� You can call the template in the imported stylesheet from a template with the
same matching XPath in the primary stylesheet using the xsl:apply-imports
element.
� The basic effect is the same as calling a template by name.
� If the imported template takes parameters, you can provide xsl:with-
param elements inside the xsl:apply-imports element.
Apply-imports
Chapter 8 Advanced XSLT
© 2008 ITCourseware, LLC Rev 4.1.1 Page 155
orbits5.xsl<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:import href="external.xsl"/><xsl:output method="html"/>
<xsl:variable name="orbit_limit" select="20" />
<xsl:template match="apollo">
<html>
<body>
<h1>Apollo Table</h1>
<table border="1">
<tr>
<th>Mission Number</th><th>Orbit Count</th>
</tr>
<xsl:apply-templates
select="mission[.//orbit/count > $orbit_limit]">
<xsl:with-param name="numberFormat" select="'1'" />
</xsl:apply-templates>
</table>
</body>
</html>
</xsl:template>
<xsl:template match="mission">
<xsl:param name="numberFormat">I</xsl:param>
<tr>
<td><xsl:value-of select="./text()" /></td>
<td>
<xsl:number value=".//orbit/count" format="{$numberFormat}"/>
</td>
</tr>
<xsl:apply-imports/></xsl:template>
</xsl:stylesheet>
Try It:Transform apollo.xml with orbits5.xsl. What changed?
Calls the same template
in external.xsl.
XSLT
Page 156 Rev 4.1.1 © 2008 ITCourseware, LLC
� It is possible that you will have multiple templates that will match a given source
node.
� Only one template will be applied as the node is processed.
� Conflicts between templates are resolved by the priority of the template.
� Imported templates have a lower priority than templates in the including
stylesheet.
� You can specify a priority with the priority attribute of the xsl:template
element, using any number other than infinity.
� The template with the higher priority number wins.
� Otherwise, a default priority is calculated by the processor.
Template Rule Conflicts
Chapter 8 Advanced XSLT
© 2008 ITCourseware, LLC Rev 4.1.1 Page 157
The formula used by XSLT processors to select matching templates is somewhat involved. The basic stepsare:
1. Find every template that could possibly match the current source document context node.
2. Rank them by import precedence and discard all but the highest precedence templates (i.e., don'tconsider imported templates if built-in templates are available).
3. For each remaining template, determine its priority:
If the xsl:template element has an explicit priority attribute, use it.Otherwise, calculate the priority using the following rules (from the XSLT recommendation):
a. If the pattern contains multiple alternatives separated by |, then it is treated equivalently to a setof template rules, one for each alternative.
b. Any templates that match on an element name or attribute name have a priority of 0.
c. Matches with the processing-instruction() function also have a priority of 0.
d. Any matches that use prefix:* have a priority of -0.25.
e. Any templates that match with comment(), node(), text(), * or @* have a priority of -0.5.
f. Everything else has the priority of 0.5.
4. If more than one template has the same priority value, the processor can either return an error to theuser or choose the template that was declared last in the document.
XSLT
Page 158 Rev 4.1.1 © 2008 ITCourseware, LLC
Extensions
� The XSLT specification allows you to add additional capabilities to yourstylesheets through extensions.
� Most XSLT processors define their own extensions.
� Most also provide a mechanism for you to create your own.
� Two types of extensions are defined: extension elements and extensionfunctions.
� Extensions are written in a programming language and are external to theXSLT processor.
� The external programs have access to the source tree and can generateoutput for the result tree.
� The xsl:stylesheet element should specify the namespace of the extension.
� For extension elements, include an extension-element-prefixes attribute.
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ext="com.example.extensions"
extension-element-prefixes="ext">
� You can use the element-available() function to test whether a given element isavailable ahead of time.
� Use this as the test value of an xsl:if or xsl:when element.
� There is also a function-available() function.
� The xsl:fallback element works kind of like an exception handler.
� It defines a template that will be used if an extension element or functiondoesn't exist.
� It must be used inside an xsl:template element and has no attributes.
Chapter 8 Advanced XSLT
© 2008 ITCourseware, LLC Rev 4.1.1 Page 159
extensions.xsl<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ext="com.example.extensions"
extension-element-prefixes="ext">
<xsl:template match="/">
<ext:doSomethingCool><xsl:fallback>
<xsl:message>
The extensions library is unavailable.
</xsl:message>
</xsl:fallback></ext:doSomethingCool>
</xsl:template>
</xsl:stylesheet>
The xsl:message element is used to send output to somewhere other than the result tree. Most processorswill send the contents of the xsl:message element to stdout. The optional terminate attribute can be set toyes or no to indicate whether to halt execution upon encountering the message.
Try It:Transform apollo.xml with extensions.xsl to see fallback processing occur.
XSLT
Page 160 Rev 4.1.1 © 2008 ITCourseware, LLC
Labs
� Create an XSLT stylesheet that reads cart.xml and outputs an HTML table with all the items that
are less than $30. The table should contain three columns: a line number, the product name, and theline total. Store the $30 limit in a variable called topPrice at the top level of the stylesheet.(Solution: purchase1.xsl)
� Modify the stylesheet so the line numbers are presented as Roman numerals.
(Solution: purchase2.xsl)
� Create a new stylesheet that contains a template named header that provides a nice header for your
HTML output. Import the stylesheet into your original stylesheet. Call the header so it is displayedabove your table.(Solutions: purchase3.xsl, external1.xsl)
� Modify the imported stylesheet and add a template that will provide the total line in the table of all
the purchased items. Pass the value of the topPrice variable to the template as a parameter. Modifythe original stylesheet so it adds the total line at the bottom of the HTML table.(Solutions: purchase4.xsl, external2.xsl)
� Modify your solution again to display the total with two decimal places.
(Solutions: purchase5.xsl, external3.xsl)
Chapter 8 Advanced XSLT
© 2008 ITCourseware, LLC Rev 4.1.1 Page 161