Is it possible to preprocess xml source within the same XSLT Stylesheet?

471 Views Asked by At

Within the same XSLT (2.0) Stylesheet and transformation I would like to:

1) first preprocess the whole XML Datasource (Add a attribute 
    with a specific  calculation to certain elements) 

and then

2: transform the changed XML Datasource with the sylesheet's templates.

How can I achieve this? A code example would be nice?

1

There are 1 best solutions below

0
potame On BEST ANSWER

Yes it is possible. One possibility would be to to proceed as follows:

<xsl:template match="/">
    <!-- store the modified content in a variable -->
    <xsl:variable name="preprocessed.doc">
        <xsl:apply-templates mode="preprocess" />
    </xsl:variable>

    <!-- process the modified contents -->
    <xsl:apply-templates select="$preprocessed.doc/*" />
</xsl:template>

<!-- first pass: sample process to add an attribute named "q" -->
<xsl:template match="*" mode="preprocess">
    <xsl:copy>
        <xsl:copy-of select="@*"/>
        <xsl:attribute name="q"><xsl:number count="*" level="any" /></xsl:attribute>
        <xsl:apply-templates mode="preprocess" />
    </xsl:copy>
</xsl:template>

<!-- "normal" processing of the modified content. It is able to used the newly processed attribute. -->

<xsl:template match="*[@q &lt;= 5]">
    <xsl:copy>
        <xsl:apply-templates />
    </xsl:copy>
</xsl:template>

<xsl:template match="*"/>
  1. In the first pass, an attribute is added, counting the element in the input XML.
  2. In the processing, we only retain the elements having the value of the q attribute set a number less or equals to 5.