Intro

XSLT (XSL for Transformations) is a W3C standard for a rule-base programming language which takes an XML document (the source tree) and transforms the data into a new document (the result tree). XSLT is manifested as an XML document (.xsl, with a type of text/xsl) called a stylesheet. An XSLT stylesheet defines and accesses different nodes in the source data (via XPath) and transforms the nodes in particular ways (via template rules in the XSLT stylesheet). XSLT can add, rename, recalculate, exclude, query, sort, and restructure nodes.

XSLT transformations are usually either template-driven or data-driven.

Template Rules

  • If the rule has no conditional statements, it most likely directs the processor to simply transform this document root element. In this case, the processor transforms the root element and then looks for a template rule that matches the next highest element in the source tree. The processor transforms that element, and then looks for the next highest element. This process continues for all the elements in the source tree.
  • If the rule contains conditional statements, the processor evaluates each statement and executes the appropriate action. Often, each conditional statement directs the XSLT processor through a series of template rules that are specific to the conditional statement. Essentially, this means that the XSLT processor ignores all template rules associated with other conditional statements.

-These two bullets were borrowed directly from Microsoft. Any paraphrasing would have harmed the conciseness!

The heart of XSLT are template rules. A template rule usually does the following:

  1. Match data (specific parts of the source tree) via an XPath expression. Usually an XSLT style sheet will first match the root element (EG: <xsl:template match="/">) or a specific element (EG: <xsl:template match="section/title">).
  2. Transform the data for output (for the result tree).
    • Create a structure of elements, attributes, text for the result tree. EG: Items not part of the XSL namespace such as <div> are interpreted as literal result elements.
    • Apply other template rules specifically (EG: <xsl:apply-templates select="guid"/>) or generally to the children of the current node (<xsl:apply-templates />). In this fashion a whole series of xsl:template elements would eventually be used.
    • Extract data from the source tree. EG: <xsl:value-of select="id('TheAnswer')"/> or <xsl:value-of select="." />.

A key concept is that xsl:template and xsl:key are the only XSL elements that use a match attribute (which specifies which nodes to apply the template upon), whereas other XSL elements such as <xsl:for-each>, <xsl:value-of>, and <xsl:apply-templates> have a select attribute (which specifies which nodes to get data from).

EG: This example takes the section elements and does 3 thing with them: It directly processes title elements that are children of section. It processes all detail elements that are descendants of section. It

<xsl:template match="section">
  <div>
    <h2><xsl:value-of select="title"/></h2>
    <xsl:apply-templates select=".//detail" />
    <xsl:apply-templates />
  </div>
</xsl:template>

Note that a XSLT stylesheet does not have to have template rule. Such a stylesheet could extract specific data directly. EG:

<xsl:stylesheet 
  version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns="http://www.w3.org/TR/xhtml1/strict">
<xsl:template match="/">
<html>
  <head>
    <title>The Answer</title>
  </head>
  <body>
    <p>The Answer: <xsl:value-of select="id('TheAnswer')"/></p>
  </body>
</html>
</xsl:template>
</xsl:stylesheet>

 

Variables and Parameters

XSLT uses the <xsl:param> and <xsl:variable> elements to as memory caches. Once the value is set for a parameter or variable, it cannot be changed until it falls out of scope. If the parameter or variable is declared as an immediate child element of <xsl:stylesheet>, then it has global scope throughout the document. If the parameter or variable is declared within a template rule, then it has local scope within its context.

The values of a parameter or variable is set using this syntax: <xsl:param name="ParameterName" select="expression">Template</xsl:param>. expression (or the content of the element if expression is not specified) may be things like a literal (EG: Smith) or a nesting of elements (EG: <a><b>sam</b><b>wise</w></a>).

A parameter or variable is referenced by its name prefixed by a dollar sign. EG: <lastName><xsl:value-of select="$lastName"/></lastName>.

The difference between an XSLT parameter and variable is that the value of a parameter can be set from outside of the XSLT style sheet or between template rules within a style sheet.

EG: Here is a variable used to hold a literal:

<xsl:template match="weather">
   <H1>Weather Readings</H1>
   <xsl:for-each select="day">
      <H2>As of <xsl:value-of select="@date"/></H2>
      <xsl:for-each select="locale">
         <xsl:variable name="placename">
             <xsl:choose>
                 <xsl:when test="@place='location1'">Midtown</xsl:when>
                 <xsl:when test="@place='location2'">Northeast</xsl:when>
                 <xsl:when test="@place='location3'">Airport</xsl:when>
                 <xsl:otherwise>[Unknown Locale]</xsl:otherwise>
             </xsl:choose>
         </xsl:variable>
         <H3><xsl:value-of select="$placename"/></H3>
      </xsl:for-each>
   </xsl:for-each>
</xsl:template>

EG: Here is a variable used to hold an XPath expression:

<xsl:variable name="average_temp" select="format-number( sum(locale/temp/high) div count(locale), '##0.00')"/>
<H2>As of <xsl:value-of select="@date"/></H2>
<P>
   Average Temperature: 
   <xsl:value-of select="$average_temp"/>&#176;F
</P>

EG: Here is a parameter getting set from another template rule:

<xsl:call-template name="some_named_template">
    <xsl:with-param name="param1" select="@some_attrib"/>
</xsl:call-template>

EG: Here is a parameter getting set from outside of the style sheet.

Step 1. Declare a global parameter. Because we will change it later, it doesn't matter what it is set to initially.

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="bgColor">black</xsl:param>
<xsl:template match="/">
bgColor = <xsl:value-of select="$bgColor"/>
</xsl:template>
</xsl:stylesheet>

Step 2. Use three XML documents to pass in a value for the parameter.

<html>
<head>
   <title>bgColor in HTML</title>
</head>
<script>
  var xslt, xml, xslTemp, xslProc;
  function load(){
     xml = new ActiveXObject("Msxml2.DOMDocument.4.0");
     xml.async = false;
     xml.load("bgColor.xsl");

     xslt = new ActiveXObject("Msxml2.FreeThreadedDOMDocument.4.0");
     xslt.async = false;
     xslt.load("bgColor.xsl");

     xslTemp = new ActiveXObject("Msxml2.XSLTemplate.4.0");
     xslTemp.stylesheet = xslt;
     
     xslProc = xslTemp.createProcessor();
     xslProc.input = xml;
     xslProc.addParameter("bgColor", "red");

     try { 
       xslProc.transform;
       result.innerHTML = xslProc.output;
     }
     catch(e)
     {
       result.innerHTML = e.description;
     }
  }
</script>
<body onload="load()">
  <div id="result"></div>
</body>

Elements

There are 35 elements in XSLT. The syntax is <xsl:element>. EG: <xsl:transform>.

Required attributes are in bold. Default attribute values are in bold.

xsl:element
and attributes
Category Notes
xsl:apply-imports instruction Invokes an overridden template rule. Used in conjunction with xsl:import. See also xsl:import.
xsl:apply-templates
    select= NodeSetExpression
    mode= QName
instruction Directs the XSLT processor to find the appropriate template to apply, based on the type and context of each selected node. If select is not specified, then xsl:apply-temlates processes all the children of the current node. Content: (xsl:sort | xsl:with-param)*.
xsl:attribute
    name= QName
    namespace= URIReference
instruction Creates an attribute node and attaches it to an output element. Must be used before child elements are added to the output element. Use when you need to compute the name of attributes in the result tree instead of just writing out the attribute literally. Content: template.

EG:

<tr>
   <xsl:attribute name="title"><xsl:value-of select="symbol"/>
     is listed on the <xsl:value-of select="@exchange"/> 
     stock exchange.
   </xsl:attribute>
   .....
</tr>
xsl:attribute-set
    name= QName
    use-attribute-sets= QNames
top-level element Defines a named set of attributes. Use with xsl:copy and xsl:element. Content: xsl:attribute*.

EG:

<xsl:attribute-set name="td-attrs">
  <xsl:attribute name="align">right</xsl:attribute>
  <xsl:attribute name="valign">top</xsl:attribute>
</xsl:attribute-set>
...
<xsl:element name="td" use-attribute-sets="table-cell-attrs">
xsl:call-template
    name= QName
instruction Invokes a template by name. The target xsl:template has to have its name attribute set. Content: xsl:with-param*.
xsl:choose instruction Provides multiple conditional testing in conjunction with the xsl:when and xsl:otherwise. Content: (xsl:when+, xsl:otherwise?)

EG: This colors rows depending on the value of an element.

<tr>
  <xsl:attribute name="style">color:
    <xsl:choose>
      <xsl:when test="price[. &lt; 25]">green</xsl:when>
      <xsl:when test="price[. &lt; 50]">blue</xsl:when>
      <xsl:otherwise>red</xsl:otherwise>
    </xsl:choose>
  </xsl:attribute>
xsl:comment instruction Generates a comment in the output. Content: template.

EG:  <xsl:comment>foo bar!</xsl:comment> makes this in the result tree: foo bar! .

xsl:copy
    use-attribute-sets= QName
instruction Copies the current node from the source to the output. Content: template.
xsl:copy-of
    select
= Expression
instruction Inserts sub-trees and result tree fragments into the result tree.
xsl:decimal-format
    name= QName
   
decimal-separator= char
   
grouping-separator= char
   
infinity= string
   
minus-sign= char
   
NaN= string
   
percent= char
   
per-mille= char
   
zero-digit= char
   
digit= char
   
pattern-separator= char
top-level element Declares a decimal-format, which controls the interpretation of a format pattern used by the format-number function.
xsl:element
    name
= Qname
   
namespace= URIRreference
   
use-attribute-sets= QNames
instruction Creates an element with the specified name in the output. Use when you need to compute the name of elements in the result tree instead of just writing out the element literally.
xsl:fallback instruction Calls template content that can provide a reasonable substitute to the behavior of the new element when encountered. Content: template.
xsl:for-each
    select= NodeSet Expression
instruction Applies a template repeatedly, applying it in turn to each node in a set. Content: (xsl:sort*, template).
xsl:if
    test= BooleanExpression
instruction Allows simple conditional template fragments. Content: template.

EG: This colors every other row.

<xsl:template match="item">
  <tr>
    <xsl:if test="position() mod 2 = 0">
       <xsl:attribute name="bgcolor">yellow</xsl:attribute>
    </xsl:if>
    <xsl:apply-templates/>
  </tr>
</xsl:template>
xsl:import
    href= URIRference
top-level element Imports another XSLT file. Like xsl:include except that the importer takes precedence over the imported.  An XML document may be connected to one and only one XSL style sheet; if more than one is connected, then only the first one is used. A stylesheet should not directly or indirectly include or import itself. May be used in conjunction with xsl:apply-imports.

EG: The importer's <div> would surround whatever the second.xsl makes if any because xsl:apply-imports is used.

<xsl:import href="second.xsl"/>
<xsl:template match="example">
  <div style="border: solid red">
     <xsl:apply-imports/>
  </div>
</xsl:template>
xsl:include
    href= URIRference
top-level element Includes another XSLT file. See also xsl:import.
xsl:key
    name= QName
    match= Pattern
    use= Expression
top-level element Declares a named key for use with the key() function in XPath expressions.
xsl:message
    terminate= "yes" | "no"
instruction Sends a text message to either the message buffer or a message dialog box. Content: template.
xsl:namespace-alias
    stylesheet-prefix= Prefix | "#default"
    result-prefix= Prefix | "#default"
top-level element Replaces the prefix associated with a given namespace with another prefix.

EG: If you want your result tree to have <xsl:stylesheet> elements then make an alias for it.

<xsl:namespace-alias stylesheet-prefix="axsl" result-prefix="xsl"/>
<xsl:template match="/">
  <axsl:stylesheet>
    <xsl:apply-templates/>
  </axsl:stylesheet>
</xsl:template>
xsl:number
    level= "single" | "multiple" | "any"
    count= Pattern
    from= Pattern
    value= NumberExpression
    format= String
    lang= NMToken
    letter-value=  "alphabetic" | "traditional"
    grouping-separator= char
    grouping-size= number
instruction Inserts a formatted number into the result tree.
xsl:otherwise instruction Provides multiple conditional testing in conjunction with xsl:choose and xsl:when. See xsl:choose. Content: template
xsl:output
    method= "xml" | "html" | "text" | QName-but-not-NCName
    version= NMToken
    encoding= String
    omit-xml-declaration= "yes" | "no"
    standalone= "yes" | "no"
    doctype-public= String
    doctype-system= String
    cdata-section-elements= QNames
    indent= "yes" | "no"
    media-type= String
top-level element Specifies options for use in serializing the result tree. It is common to make the first child of the root element of an XSL file an output method declaration.
xsl:param
    name= QName
   
select= Expression
top-level element Declares a named parameter for use within a stylesheet. Allows you to specify a default value. Content: template.
xsl:preserve-space
    elements= Tokens
top-level element Preserves white space in a document.
xsl:processing-instruction
    name= NCName
instruction Generates a processing instruction in the output. Content: template.

EG: <xsl:processing-instruction name="xml-stylesheet">href="site.css" type="text/css"</xsl:processing-instruction>  makes this in the result tree: <?xml-stylesheet href="site.css" type="text/css"?>.

msxsl:script
    language= "language-name"
    implements-prefix= "prefix of user's namespace"
instruction Defines global variables and functions for script extensions.
xsl:sort
   
select= StringExpression
    lang= NMToken
    data-type= "text" | "number" | QName
    order= "ascending" | "descending"
    case-order= "upper-first" | "lower-first"
instruction Specifies sort criteria for node lists selected by xsl:for-each or xsl:apply-templates. xsl:sort is declared as a child of an xsl:for-each or an xsl:apply-templates. Multiple xsl:sort elements are allowed for each template rule or each loop. When used in xsl:for-each, then xsl:sort elements must occur before any other child elements.

EG:

<xsl:template match="employees">
  <ul>
    <xsl:apply-templates select="employee">
      <xsl:sort select="name/family"/>
      <xsl:sort select="name/given"/>
    </xsl:apply-templates>
  </ul>
</xsl:template>

<xsl:template match="employee">
  <li>
    <xsl:value-of select="name/given"/>
    <xsl:text> </xsl:text>
    <xsl:value-of select="name/family"/>
  </li>
</xsl:template>
xsl:strip-space
    elements= Tokens
top-level element Strips white space from a document.
xsl:stylesheet
    id= id
    extension-element-prefixes= Tokens
    exclude-result-prefixes= Tokens
    version= number
    xmlns:xsl=namespace
root Specifies the root document element of an XSLT file. The document element contains all other XSLT elements. Usu. version="1.0" and xmlns:xsl="http://www.w3.org/1999/XSL/Transform". Content: (xsl:import*, top-level-elements). The following variations are not as common:
  • xmlns:fo="http://www.w3.org/1999/XSL/Format". Ha!
  • xmlns:user="http://www.myCompany.com/myNamespace".
  • xmlns="urn:schemas-myCompany-com:xslt".
  • xmlns:msxsl="urn:schemas-microsoft-com:xslt". If you are using some of the non-standard XSLT features of MSXML.
xsl:template
    name= QName
    match= Pattern
    priority= Number
    mode= QName
top-level element Defines a reusable template for generating the desired output for nodes of a particular type and context. Content: (xsl:param*, template).

If an XSLT stylesheet does not have a template rule, then the following template rule are implied:

<xsl:template match="*|/">
  <xsl:apply-templates/>
</xsl:template>
<xsl:template match="*|/" mode="m">
  <xsl:apply-templates mode="m"/>
</xsl:template>
<xsl:template match="text()|@*">
  <xsl:value-of select="."/>
</xsl:template>
<xsl:template match="processing-instruction()|comment()"/>
<!-- The last one says to do nothing -->
xsl:text
    disable-output-escaping= "yes" | "no"
instruction Generates text in the output. Use disable-output-escaping="yes" sparingly. Content: #PCDATA.

EG: If disable-output-escaping="yes", and the text is something like &, then the result tree will return & instead of the usual &amp; .

xsl:transform
    id= id
    extension-element-prefixes= Tokens
    exclude-result-prefixes= Tokens
    version= number
    xmlns:xsl=namespace
root Synonym for xsl:stylesheet.
xsl:value-of
    select= StringExpression
    disable-output-escaping= "yes" | "no"
instruction Inserts the value of the selected node as a text node. See also xsl:text.

EG:

<xsl:template match="person">
  <p>
   <xsl:value-of select="given-name"/>
   <xsl:text> </xsl:text>
   <xsl:value-of select="@family-name"/>
  </p>
</xsl:template>
xsl:variable
    name= QName
   
select= Expression
top-level element
and instruction
Specifies a value bound in an expression. Content: template.
xsl:when
    test= BooleanExpression
instruction Provides multiple conditional testing in conjunction with xsl:choose and xsl:otherwise. Content: template. See xsl:choose.
xsl:with-param
    name= QName
   
select= Expression
instruction Passes a parameter to a template. Content: template.

Functions

XSLT functions return values. XSLT can also use XPath function.

XPath Function Returns Note
current() node-set Returns a node set that has the current node as its only member.
document(object, node-set) node-set Provides a way to retrieve other XML resources from within the XSLT style sheet beyond the initial data provided by the input stream.
element-available(string) boolean Returns True if and only if the expanded-name is the name of an instruction.
format-number(number, string, string) string Converts the first argument to a string using the format pattern string specified by the second argument. EG: <xsl:value-of select="format-number($bookAverage, '#.00')"/>.
function-available(string) boolean Returns True if the function is available in the function library.
generate-id(node-set) string Returns a string that uniquely identifies the node in the node-set argument that is first in document order.
key(name, value) node-set Retrieves elements previously marked with a xsl:key.
msxsl:node-set(string)   Converts a tree into a node set. The resulting node always contains a single node and the root node of the tree.
system-property(string) object Returns an object representing the value of the system property identified by the name.
unparsed-entity-uri(string name) string Returns declarations of unparsed entities in the DTD of the source document.

Miscellany

Page Modified: (Hand noted: ) (Auto noted: )