XML technologies / XSLT / XSLT 3.0 / XSLT streaming / Accumulators
Accumulators were introduced in XSLT 3.0 to collect, process and store streamed data for later use. They are not restricted to streaming and can also be used without it.
Applied to a tree, accumulators provide two additional values for each node, called pre-descendant and post-descendent values, accessible through functions accumulator-before() and accumulator-after().
Accumulator values for a tree can be obtained by evaluating rules in the xsl:accumulator declaration or copying corresponding nodes in another tree. Copying values is supported by functions snapshot(), copy-of() or instruction xsl:copy-of with copy-accumulators="yes" to create accumulator values. Values are also created by the implicit call to function snapshot() in instruction xsl:merge.
This example, adapted from XSL Transformations (XSLT) Version 3.0., illustrates numbering figures within a chapter. Streaming does not allow instruction xsl:number, so accumulators provide equivalent functionality.
Code example: introductory accumulator example.
<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>
<xsl:mode streamable="yes"/>
<xsl:template match="figure">
<xsl:apply-templates/>
<p>Figure <xsl:value-of select="accumulator-before('figNr')"/></p>
</xsl:template>Numbering figures with accumulators in streaming mode.
Line 1: Before using accumulator values, declare a top-level accumulator with xsl:accumulator. Attribute name assigns its name. Attribute as determines how the results of the initial-value and select expressions are converted. Streaming processing requires streamable="yes".
Here the name is figNr. Figure numbers are processed as integers according to defined rules. <xsl:accumulator-rule match="chapter" select="0"/> resets the value to 0 for each chapter, and <xsl:accumulator-rule match="figure" select="$value + 1"/> increments it for each figure.
Line 6: A template is defined to process all figure elements in streaming mode.
Line 8: The paragraph appends a number to the figure label. The result of select is processed according to accumulator rules and converted to an integer. Function accumulator-before() returns the accumulator’s value before processing further child nodes of the current node.