Greenev
Greenev

Reputation: 909

Count elements after the document gets transformed using XSLT with streaming

To complete the task from the previous question I also need to count certain elements of the document I am getting after the transformation has been done.
Typically, when dealing with small documents, one could just put the initial output to a variable and then apply templates to it, something like

<xsl:template match=/*>
    <xsl:variable name="phase1">
        <Transformed>
            ...
        </Transformed>
    </xsl:variable>

    <xsl:apply-templates mode="step2" select="$phase1/*"/>

</xsl:template>

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

<xsl:template match="/Transformed/DocumentTotal/text()" mode="step2">
   <xsl:value-of select="count(/Transformed//*[some predicate here]"/>
</xsl:template>

But I have to be able to process large documents, so I am neither want to copy result to a variable, nor to process it in non-streamable mode. I took a look at <xsl:accumulator and already wrote one allows me to count certain elements in source document, but now I got stuck having no idea how to perform such a count of the elements in the result document, could someone help me, please?

Upvotes: 0

Views: 164

Answers (1)

Michael Kay
Michael Kay

Reputation: 163595

There's a range of techniques for this, none of them especially satisfactory. They include:

(a) run another pass over the output document: (a1) within the same XSLT stylesheet, using a variable (a2) in a second XSLT stylesheet (a3) using some technology other than XSLT, e.g. a post-processing SAX filter

(b) run some computation on the input document that works out how many items will be present in the result, independently of actually producing those results. The viability of these of course varies greatly depending on the actual conditions.

(c) use some processor extension that allows you to increment a counter as a side-effect of generating an output item (for example saxon:assign - this is the principal use case for retaining that instruction).

Upvotes: 1

Related Questions