Gen 3 features you should love!

Friday 16th September 2022

XSLT Modes

Modes

Modes are a way of assigning templates to a set

Modes Example


      <xsl:stylesheet version="2.0">
        <xsl:template match="part">
          <xsl:apply-templates mode="meta" select="."/>
          <xsl:apply-templates mode="content" select="."/>
        </xsl:template>
        <xsl:template match="part|chapter|section" mode="meta">
          <metadata>
            <xsl:apply-templates mode="#current"/>
          </metadata>
        </xsl:template>
        <xsl:template match="chapter/*|part/*|section/*" mode="meta"/>
        <xsl:template match="part/title" mode="meta">
          <meta name="title">
            <xsl:apply-templates mode="#default"/>
          </meta>
        </xsl:template>
        <xsl:template match="part" mode="content">
          <body>
            <xsl:apply-templates/>
          </body>
        </xsl:template>
      </xsl:stylesheet>
	  

xsl:mode - Declaring Modes


      <xsl:mode warning-on-no-match="true"/>
      <xsl:mode name="copy" on-no-match="shallow-copy" warning-on-no-match="false"/>
    

XSLT 3 adds a way to define some common mode options. The following attributes may be used:

name
Mode names can include prefixes; a mode declaration without a name applies to the default unnamed mode.
on-multiple-match
Options are use-last (in document order of the stylesheet) or fail (throw an error). Defaults to use-last
warning-on-multiple-match
Whether to show warning messages if an item is matched by more than one template; uses one of yes, no, true, false, 1, 0.
on-no-match
Changes the default built-in template behaviours - more on the following slides!
warning-on-no-match
Whether to show warning messages if an item is not matched by any templates; uses the same values as warning-on-multiple-match.

@on-no-match: over-riding the default templates

There are six options for when no template explicitly matches an item: these essentially replace the default built-in templates we have already seen:

@on-no-match="text-only-copy"

The default behaviour, equivalent to the built-in templates:


      <xsl:template match="document-node()|element()">
        <xsl:apply-templates/>
      </xsl:template>
      <xsl:template match="text()|@*">
        <xsl:value-of select="string(.)"/>
      </xsl:template>
      <xsl:template match=".[. instance of xs:anyAtomicType]">
        <xsl:value-of select="string(.)"/>
      </xsl:template>
      <xsl:template match="processing-instruction()|comment()|namespace-node()"/>
      <xsl:template match=".[. instance of function(*)]"/>
      <xsl:template match=".[. instance of array(*)]">
        <xsl:apply-templates mode="#current" select="?*"/>
      </xsl:template>
    

@on-no-match="shallow-copy"

Replicates what is sometimes known as the identity template.

Equivalent to replacing the built-in templates with:


      <xsl:template match=".">
        <xsl:copy>
          <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
      </xsl:template>
    

@on-no-match="shallow-skip"

Continues recursing until a matching template is found without copying to output tree

Equivalent to replacing the built-in templates with:


      <xsl:template match="document-node()|element()">
        <xsl:apply-templates select="@* | node()"/>
      </xsl:template>
      <xsl:template match="."/>
      <xsl:template match=".[. instance of array(*)]">
        <xsl:apply-templates select="?*"/>
      </xsl:template>
    

@on-no-match="deep-copy"

Copies entire input tree to the output without applying templates further.

Equivalent to replacing the built-in templates with:


      <xsl:template match=".">
        <xsl:copy-of select="."/>
      </xsl:template>
    

@on-no-match="deep-skip"

Equivalent to replacing the built-in templates with:


      <xsl:template match="."/>
      <xsl:template match="document-node()">
        <xsl:apply-templates/>
      </xsl:template>
    

@on-no-match="fail"

Any un-matched node in the input tree results in an error being thrown.

Equivalent to replacing the built-in templates with:


      <xsl:template match=".">
        <xsl:message terminate="yes" error-code="err:XTDE0555"/>
      </xsl:template>
    

Arrays


			$months(3)
			(: For an array containing month names in order, this returns "March" :)
		

Like other XPath values, arrays are immutable - functions that 'change' arrays are actually returning new arrays.

Creating Arrays

let $months := ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
let $months := array { ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") }

Arrays and Sequences

Arrays and sequences appear to have a similar function, but there are some important differences.

In particular, Sequences collapse, whereas Arrays can't:

Sequences

						("one", (), "two", "three")[3]    (: returns "three":)
						("one", (2, 3), "four", "five")[2] (: returns 2 :)
					
Arrays

						["one", (), "two", "three"](3)    (: returns "two" :)
						["one", (2, 3), "four", "five"](2) (: returns (2, 3) :)
					

You can also nest arrays within arrays:


			let $curvature := [
			  [0, "a"],
			  ["b", 0]
			]
			return $curvature(1)(2)     (: returns "a" :)
		

Maps

Maps are functions which take an atomic value, or key, and return an associated sequence.

Maps can be constructed with the map {} keyword:


			let $month := map {
				"January" : 31,	  "February": 28,   "March"    : 31,
				"April"   : 30,   "May"     : 31,   "June"     : 30, 
				"July"    : 31,   "August"  : 31,   "September": 30, 
				"October" : 31,   "November": 30,   "December" : 31
			}
		

Retrieving Map values

We can retrieve values using the map as a function:

$month("March") (: returns 31 :)

Or, if the key is an integer or string, the lookup operator ?:

$month?March    (: returns 31 :)

If no key is found, the empty sequence is returned:

$month(31)      (: returns () :)

Map Functions

We can use the map:keys() function to return a sequence of the keys.

map:keys($month) (: returns ("January", "February", "March", ...) :)

The order that keys are returned in is not guaranteed to be the same each time

map:size() returns the number of entries in the map:

map:size($month) (: returns 12 :)

Like other XPath values, maps are immutable - functions that 'change' maps are actually returning new maps.

Map functions use the map namespace: http://www.w3.org/2005/xpath-functions/map.

Merging Maps


			let $map1 := map { 1: 'true', 0: 'false' }
			let $map2 := map { 1: 'yes' , 0: 'no'    }
			map:merge( ($map2, $map1) )
			  (: returns map {1: 'yes', 0: 'no'} :)
			map:merge( ($map1, $map2), map {'duplicates':'combine'})
			  (: returns map {1: ('true', 'yes'), 0: ('false', 'no') } :)
		

Map Instructions

As well as supporting XPath map syntax, XSLT introduces two instructions that allow maps to be created using e.g. xsl:apply-templates:

xsl:map
MUST contain a sequence of maps, which it merges; equivalent to an xpath map merge. Duplicates are rejected.
xsl:map-entry
Creates a simple map with a single key and value.

      <xsl:template match="employees">
        <xsl:map>
          <xsl:apply-templates/>
        </xsl:map>
      </xsl:template>
      
      <xsl:template match="employee">
        <xsl:map-entry key="@id" select="."/>
      </xsl:template>
    

The Type of a Map

It is possible to not only specify that an item's type is a map, but also to specify what types the key and values of that map are:


      <xsl:variable name="my-map" as="map(xs:integer, xs:string)"/>
    

      map{
        0 : 'false',
        1 : 'true'
      }
    

      map{
        0      : false(),
        'true' : 1
      }
    

XSLT Accumulators

Accumulators define series of values with nodes of a tree.

Declaring an Accumulator

Accumulators are declared using the xsl:accumulator instruction, which contains one or more xsl:accumulator-rule instructions.

The value of an accumulator can access the previous value using the special pseudo-variable $value

This example shows an accumulator which gives a figure number for figures within a chapter:


      <xsl:accumulator name="figNr" as="xs:integer" initial-value="0" streamable="yes">
        <xsl:accumulator-rule match="chapter" select="0"/>
        <xsl:accumulator-rule match="figure" select="$value + 1"/>
      </xsl:accumulator>
    

You will also need to add the accumulator to any modes where they are used:


      <xsl:mode name="figures" use-accumulators="figNr"/>
    

Pre and Post Descent

Each node is associated with up to two values

pre-descent
returned using the accumulator-before() function
Can be set: xsl:accumulator-rule/@phase = "start" (which is the default)
post-descent
returned using the accumulator-after() function
Can be set: xsl:accumulator-rule/@phase = "end"

We can see how these are used by example:

Accumulator example: simple word count


      <xsl:accumulator name="wc" initial-value="0" as="xs:integer">
        <xsl:accumulator-rule match="text()" select="$value + count(tokenize(., '\s+'))"/>
      </xsl:accumulator>
      
      <xsl:template match="section">
        <xsl:apply-templates/> 
        <p class="wordcount">(words: <xsl:value-of select="accumulator-after('wc') - accumulator-before('wc')"/>)</p>
      </xsl:template>
    

accumulator-before('wc') will give the total word count of the whole input tree at the start of the current context node; accumulator-after('wc') gives the total word including the current context node.

Iterating in XSLT

The xsl:iterate instruction

The xsl:iterate instruction allows each item in an input sequence to be processed sequentially, optionally passing values from one iteration to the next.

It is entirely possible to reproduce these effects using templates; however, xsl:iterate enforces tail recursion, which can help ensure clean, efficient code:


      <xsl:variable name="number" select="4" as="xs:integer"/>
      <xsl:iterate select="reverse(1 to $number)">
        <xsl:param name="product" select="1" as="xs:integer"/>
        <xsl:on-completion select="$product"/>
        <xsl:message expand-text="yes">Multiplying {$product} by {.}</xsl:message>
        <xsl:next-iteration>
          <xsl:with-param name="product" select=". * $product"/>
        </xsl:next-iteration>
      </xsl:iterate>
    

xsl:iterate - Parameters

Parameters can be passed between stages of the iteration in the same way that they are passed between templates.

Usually, parameters will need to be given an initial value (even if that value is an empty sequence or map):


      <xsl:param name="product" select="1" as="xs:integer"/>
    

xsl:iterate - The results of an iteration

An iteration instruction can contain a sequence constructor - in our example, a message:


      <xsl:message expand-text="yes">Multiplying {$product} by {.}</xsl:message>
    

The resulting sequence will be output, followed by the sequences produced by either xsl:on-completion or xsl:break, if present.

xsl:iterate - Calling the next iteration

After the sequence constructor for a given stage of the iteration is generated, the xsl:next-iteration can be used to 'update' the values of parameters for the next stage of iteration:


      <xsl:next-iteration>
        <xsl:with-param name="product" select=". * $product"/>
      </xsl:next-iteration>
    

xsl:next-iteration must be in the tail position within the iteration: this normally means that it should either be the last instruction, or part of a conditional expression (xsl:if or xsl:choose) which is itself the last instruction.

xsl:iterate - Completing an iteration

When the input sequence is exhausted, the xsl:on-completion instruction is evaluated (either using @select or a contained sequence constructor) and returned:


      <xsl:on-completion select="$product"/>
    

xsl:iterate - Breaking an iteration

It is possible to end a recursion early using the xsl:break instruction.

This example outputs members of an array until an empty sequence is encountered:


      <xsl:variable name="array" select="[ 1, 2, 3, (), 4 ]" as="array(*)"/>
      <xsl:iterate select="1 to array:size($array)">
        <xsl:choose>
          <xsl:when test="empty($array(.))">
            <xsl:break/>
          </xsl:when>
          <xsl:otherwise>
            <xsl:sequence select="$array(.)"/>
          </xsl:otherwise>
        </xsl:choose>
      </xsl:iterate>  <!-- Returns (1, 2, 3) -->
    

xsl:break must be in the tail position within the iteration: this normally means that it should either be the last instruction, or part of a conditional expression (xsl:if or xsl:choose) which is itself the last instruction.