Developing High-Quality XSLT Stylesheets
Friday 16th September 2022
Friday 16th September 2022
Predicate patterns introduces in XSLT 3 use the self axis . to match any item; an XPath predicate can then specify exactly what is matched.
This allows us to use matching templates on more than just node types - we can match on numerics, strings - even functions like maps and arrays!
<!-- output maps as json -->
<xsl:template match=".[. instance of map(*)]">
<xsl:value select="serialize(., map{'method':'json','indent':true()})"/>
</xsl:template>
NB not all maps can be serialised to json!
You can match using the existence of a map key or its value:
<xsl:template match=".[?set='footnotes']">
<!-- footnote handling -->
</xsl:template>
This template will only match on a map with a set key containing the value footnotes
The following items are all 'deemed empty':
* Attributes do not count as child nodes!
xsl:on-emptyThis instruction contains instructions for a sequence. This sequence is only output if all of the previous sibling instructions produce empty results.
<xsl:apply-templates select="country"/>
<xsl:on-empty>
<p>No countries found.</p>
</xsl:on-empty>
You can only use one xsl:on-empty in any given sequence constructor.
xsl:on-non-emptyThis instruction contains instructions for a sequence. This sequence is only output if any sibling instruction produces non-empty results*
<xsl:apply-templates select="cost"/>
<xsl:on-non-empty>
<p><strong>total:</strong> <xsl:value-of select="sum(cost)"/></p>
</xsl:on-non-empty>
Except for other xsl:on-non-empty or xsl:on-empty instructions!
xsl:where-populatedThis instruction is a wrapper around other instructions that create a sequence. The resulting sequence is only produced if it is not empty
Example - HTML lists:
<xsl:where-populated>
<ul class="ticklist">
<xsl:apply-templates/>
</ul>
</xsl:where-populated>
This ul element is only produced in the output tree where li are generated by the use of xsl:apply-templates; the @class does not stop the node from being empty.
<div id="students">
<xsl:where-populated> <!-- no table without thead/tbody -->
<table>
<xsl:on-non-empty><!-- no thead without tbody -->
<thead><tr><th>Name</th><th>Age</th></tr></thead>
</xsl:on-non-empty>
<xsl:where-populated><!-- no tbody without tr -->
<tbody>
<!-- populates table rows -->
<xsl:apply-templates select="student"/>
</tbody>
</xsl:where-populated>
</table>
</xsl:where-populated>
<xsl:on-empty> <!-- output if no table. -->
<p>There are no students</p>
</xsl:on-empty>
</div>
xsl:elementxsl:element allows you to create new elements in the output dynamically. You
can use this to control the namespace of the output element as well as the input.
<xsl:template match="*">
<xsl:element name="{local-name(.)}" namespace="http://my.shiny.namespace.com/">
<xsl:apply-templates/>
</xsl:element>
</xsl:template>
Note that only the namespace is guaranteed - the prefix will depend on how your namespaces are declared in the output tree!
xsl:attributexsl:attribute is much like xsl:element except that it creates
attributes.
<xsl:template match="country">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="population|gdp">
<xsl:attribute name="{local-name(.)}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
The previous slides showed a little bit of new syntax:
<xsl:element name="{local-name()}"/>
The code in braces - {local-name()} is an attribute value template.
Because we can't use xsl:apply-value-of inside an attribute we use AVTs
instead.
As of XSLT 3, you can also use these braces to evaluate XPath in general text. This
can be turned on (or off) by specifying @expand-text on an ancestor instruction:
<xsl:text expand-text="yes">The table with id "{@id}" has {$footnote-count} footnotes.</xsl:text>
XSLT offers two statements for building libraries:
xsl:import
xsl:include
xsl:include loads another stylesheet as a library.
Templates in the included library have the same precedence as those in the including file.
xsl:include can be placed anywhere that xsl:template can
be.
<xsl:stylesheet>
<xsl:template match="para"> … </xsl:template>
<xsl:include href="library.xsl"/>
</xsl:stylesheet>
xsl:import loads another stylesheet as a library.
Templates in the imported library have lower precedence those in the including file.
xsl:import statements must be the first children of
xsl:stylesheet.
<xsl:stylesheet>
<xsl:import href="library.xsl"/>
<xsl:template match="para"> … </xsl:template>
</xsl:stylesheet>
Consider the following input:
<fn class="warning">Don't do this at home!</fn>
Both of these templates match; which one does the processor choose?
<xsl:template match="fn">
<p class="footnote">
<xsl:apply-templates/>
</p>
</xsl:template>
<xsl:template match="*[@class eq 'warning']">
<div class="yellow-border">
<xsl:apply-templates/>
</div>
</xsl:template>
<div class="yellow-border">Don't do this at home!</div>
The XSL engine picks which template matches based on priority. A template's priority is:
xs:decimal valueThe rules for default priorities are a little complex, but there are only a few values, summarized here:
| Priority | Examples | Notes |
|---|---|---|
-1.00 |
|
Predicate Patterns without Predicates |
-0.50 |
|
Wildcard matches and generic node tests |
-0.25 |
|
Wildcard match on element name but not namespace, or vice versa |
0.00 |
|
Named nodes, or nodes of a particular type |
0.25 |
|
Named nodes, including type |
0.50 |
The 'default' default priority! | |
1.00 |
|
Predicate Pattern with Predicates |
You can override the priority using @priority. Any priority greater than 1 will always match in preference to a default priority.
<xsl:template match="fn" priority="2">
<p class="footnote">
<xsl:apply-templates/>
</p>
</xsl:template>
<xsl:template match="*[@class eq 'warning']">
<div class="yellow-border">
<xsl:apply-templates/>
</div>
</xsl:template>
<p class="footnote">Don't do this at home!</p>
xsl:next-match and xsl:apply-imports
xsl:next-match and xsl:apply-imports both provide a way to fall back to common functionalityxsl:next-match
<fn class="warning">Don't do this at home!</fn>
<xsl:template match="element(fn)">
<p class="footnote">
<xsl:apply-templates/>
</p>
</xsl:template>
<xsl:template match="*[@class eq 'warning']">
<div class="yellow-border">
<xsl:next-match/>
</div>
</xsl:template>
<div class="yellow-border">
<p class="footnote">Don't do this at home!</p>
</div>
xsl:next-matchThe XSLT processor will take all matching templates and eliminate using the following criteria, in order:
xsl:modedeclaration*, use the last template defined in document order* The other available option is to fail with a dynamic error.
xsl:apply-importsSimilar to xsl:next-match, except only stylesheets imported by the current template's stylesheet are considered
xsl:modedeclaration, use the last template defined in document orderXSLT has three statements for flow control:
xsl:ifxsl:for-eachxsl:choose with two child elements:
xsl:whenxsl:otherwiseYou will write better code if you avoid using any of these, with a few particular exceptions
xsl:ifxsl:if allows you to make one-decisions. The code inside the
xsl:if statement is evaluated when the test attribute
evaluates to a true value.xsl:else!
<xsl:if test="…">
<!-- do something -->
</xsl:if>
xsl:ifxsl:if can almost always be replaced by a template
that uses a predicate match. This encourages the use of small templates and matching.
Small templates and extensive use of matching leads to fewer special cases. In turn,
this leads to easier maintenance and easier to comprehend code.
<xsl:template match="emb">
<headword>
<xsl:if test="@embtype">
<xsl:attribute name="role" select="@embtype"/>
</xsl:if>
<xsl:apply-templates/>
</headword>
</xsl:template>
Would be better as:
<xsl:template match="emb">
<headword>
<xsl:apply-templates select="node()|@embtype"/>
</headword>
</xsl:template>
<xsl:template match="emb/@embtype">
<xsl:attribute name="role" select="@embtype"/>
</xsl:template>
xsl:choosexsl:choose provides a switch/case statement for XSLT. It could be used
to provide a if/else type statement. xsl:choose has two child elements
— xsl:when and the optional xsl:otherwise.xsl:choose must contain at least one xsl:when
statement (just one makes it the same as a xsl:if). Each
xsl:when statement must have a test attribute.xsl:otherwise statement lets you define a fallback
case.
<xsl:choose>
<xsl:when test="…">…</xsl:when>
<xsl:when test="…">…</xsl:when>
<xsl:otherwise>…</xsl:otherwise>
</xsl:choose>
xsl:choose (cont)We could use xsl:choose to define the output based on some data value in the
input. We can use it to decide the type of mark-up the emphasised parts of a
paragraph:
<para>My organisation believes in <emphasis role="italic">synchronised</emphasis> third-generation projections. We need to get <emphasis role="bold">on-message</emphasis> about our four-dimensional monitored concepts.</para>
<p>My organisation believes in <em>synchronised</em> third-generation projections. We need to get <strong>on-message</strong> about our four-dimensional monitored concepts.</p>
xsl:chooseWe could convert that using xsl:choose:
<xsl:template match="emphasis">
<xsl:choose>
<xsl:when test="@role = 'italic'">
<em><xsl:apply-templates/></em>
</xsl:when>
<xsl:when test="@role = 'bold'">
<strong><xsl:apply-templates/></strong>
</xsl:when>
</xsl:choose>
</xsl:template>
But suppose a new version of the document arrives with added emphasis:
<para>My organisation believes in <emphasis role="italic">synchronised</emphasis> third-generation projections. We need to get <emphasis role="bold">on-message</emphasis> about our four-dimensional <emphasis role="underline">monitored</emphasis> concepts.</para>
What do we do?
xsl:chooseIf we were to continue using xsl:choose we would have to edit it:
<xsl:template match="emphasis">
<xsl:choose>
<xsl:when test="@role = 'italic'">
<em><xsl:apply-templates/></em>
</xsl:when>
<xsl:when test="@role = 'bold'">
<strong><xsl:apply-templates/></strong>
</xsl:when>
<!-- need to add this -->
<xsl:when test="@role = 'underline'">
<span class="underline"><xsl:apply-templates/></span>
</xsl:when>
</xsl:choose>
</xsl:template>
xsl:chooseOf course, if we did this right the first time around:
<xsl:template match="emphasis[@role='italic']">
<em><xsl:apply-templates/></em>
</xsl:template>
<xsl:template match="emphasis[@role='bold']">
<strong><xsl:apply-templates/></strong>
</xsl:template>
Now, we just need to add:
<xsl:template match="emphasis[@role='underline']">
<span class="underline"><xsl:apply-templates/></span>
</xsl:template>
It's always better to add a template than to change a working one - less chance of code breaking.
xsl:if or xsl:chooseWhen you want your output to depend on a template parameter:
<xsl:template match="contributor">
<xsl:param name="graph" tunnel="yes" as="map(*)"/>
<xsl:if test="$graph?corresp">
<xsl:apply-templates select="." mode="contributor"/>
</xsl:if>
</xsl:template>
xsl:if or xsl:choose (continued)As part of a tail recursion, e.g. in xsl:function or xsl:iterate:
<xsl:function name="ex:factorial" as="xs:integer">
<xsl:param name="x" as="xs:integer"/>
<xsl:sequence select="ex:factorial($x, 1)"/>
</xsl:function>
<xsl:function name="ex:factorial" as="xs:integer">
<xsl:param name="x" as="xs:integer"/>
<xsl:param name="product" as="xs:integer"/>
<xsl:choose>
<xsl:when test="$x le 1">
<xsl:sequence select="$product"/>
</xsl:when>
<xsl:otherwise>
<xsl:sequence select="ex:factorial($x - 1, $product * $x)"/>
</xsl:otherwise>
</xsl:choose>
</xsl:function>
xsl:for-eachxsl:for-each operates like a 'for' loop in any language that can process
lists.
Along with xsl:apply-templates, xsl:for-each
sets the context node to be the currently selected element.
<xsl:for-each select="header/row">
<tr>
<xsl:copy-of select="@id"/>
<xsl:for-each select="entry">
<th>
<xsl:copy-of select="@id"/>
<xsl:value-of select="."/>
</th>
</xsl:for-each>
</tr>
</xsl:for-each>
It is very tempting to use xsl:for-each extensively. Try not to - nested
xsl:for-each loops tend to get very hard to maintain.
xsl:for-eachxsl:for-each can always be replaced with
xsl-apply-templates. Working in a style that leads to the creation of
many small templates will make maintenance simpler and will dramatically reduce
the
chances of a need to refactor the stylesheet.
The previous example could be better written as:
<xsl:apply-templates select="header/row"/>
<xsl:template match="row">
<tr>
<xsl:apply-templates select="@id|entry"/>
</tr>
</xsl:template>
<xsl:template select="entry">
<th>
<xsl:apply-templates select="@id|node()"/>
</th>
</xsl:template>
<xsl:template match="@id">
<xsl:copy/>
</xsl:template>
xsl:for-eachTL;DR - don't! Use xsl:apply-templates (or possibly xsl:iterate) instead.
In rare situations, you might need to use xsl:for-each instead of xsl:iterate when:
xsl:for-each to be processed in parallel for each value of the sequence.