XML technologies / XSLT / XSLT Cookbook / Code generation / XSLT generated from XSLT

(Excerpt from “XSLT Kochbuch” by Sal Mangano)

Problem

You want to generate XSLT from another XML representation, or transform XSLT or pseudo-XSLT into real XSLT.

Solution

Two XSLT control-structure limitations sometimes bother me: no if-then-elsif-else construct and no true loop construct. I know xsl:choose and xsl:for-each, but both fall short. With xsl:choose, element choose does little except impose another nesting level. And xsl:for-each is iteration, not a real loop. Emulating loops with variables needs recursion or the Piez method; see recipe Duplicating a string n times, which is difficult.

This XSLT-to-XSLT transformation pretends XSLT has elements xslx:elsif, xslx:else and xslx:loop. Since it does not, generate a stylesheet converting this pseudo-XSLT to real XSLT. Having xsl:if alongside xslx:if is awkward, but using the standard XSLT namespace for custom extensions would be wrong. Perhaps these elements will enter the standard someday:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xslx="http://www.ora.com/XSLTCookbook/ExtendedXSLT" >
  <xsl:output method="text"/>
  <xsl:template match="foo">
    <xslx:if test="bar">
      <xsl:text>In der Nähe von foo werden Sie oft eine bar finden!</xsl:text>
    </xslx:if>
    <xslx:elsif test="baz">
      <xsl:text>Ein baz ist ein sicheres Zeichen von Besessenheit.</xsl:text>
    </xslx:elsif>
    <xslx:else>
      <xslx:loop param="i" init="0" test="$i &lt; 10" incr="1">
        <xsl:text>Hmm, ich habe nichts zu sagen, aber das 10-mal.</xsl:text>
      </xslx:loop>
    </xslx:else>
    <xslx:loop param="i" init="10" test="$i &gt;= 0" incr="-1">
      <xslx:loop param="j" init="10" test="$j &gt;= 0" incr="-1">
        <xsl:text>&#xa;</xsl:text>
        <xsl:value-of select="$i * $j"/>
      </xslx:loop>
    </xslx:loop>
    <xslx:if test="foo">
      <xsl:text>foo foo! Niemand sagt foo foo!</xsl:text>
    </xslx:if>
    <xslx:else>
      <xsl:text>Na ja, also gut!</xsl:text>
    </xslx:else>
  </xsl:template>
</xsl:stylesheet>

This transformation generates real XSLT from pseudo-XSLT. For simplicity, it performs no semantic checks, such as multiple clauses xsl:else on a single xsl:if or repeated parameters in nested loops:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xslx="http://www.ora.com/XSLTCookbook/ExtendedXSLT" xmlns:xso="dummy" >
  <!-- Verwende die Identitätstransformation wieder, um reguläres XSLT aus einer Quelle zu einem Ziel zu kopieren. -->
  <xsl:import href="../util/copy.xslt"/>
  <!-- Lassen Sie den Prozessor KEINE Formatierung vornehmen, indem Sie indent = yes benutzen, weil das die xsl:text-Knoten vermasselt -->
  <xsl:output method="xml" version="1.0" encoding="UTF-8" />
  <!-- Wir benutzen außerdem xso als Alias, wenn wir xslt-Elemente wörtlich ausgeben müssen -->
  <xsl:namespace-alias stylesheet-prefix="xso" result-prefix="xsl"/>
  <xsl:template match="xsl:stylesheet | xsl:transform">
    <xso:stylesheet>
      <!-- Der erste Durchgang behandelt die if-elsif-else-Übersetzung und die Konvertierung von xslx:loop in benannte Template-Aufrufe -->
      <xsl:apply-templates select="@* | node( )"/>
      <!-- Der zweite Durchgang behandelt die Konvertierung von xslx:loop in rekusive benannte Templates -->
      <xsl:apply-templates mode="loop-body" select="//xslx:loop"/>
    </xso:stylesheet>
  </xsl:template>
  <!-- Wir suchen nach xslx:if mit entsprechendem xslx:elsif oder xslx:else -->
  <xsl:template match="xslx:if[following-sibling::xslx:else or following-sibling::xslx:elsif]">
    <xsl:variable name="idIf" select="generate-id( )"/>
    <xso:choose>
      <xso:when test="{@test}">
        <xsl:apply-templates select="@* | node( )"/>
      </xso:when>
      <!-- Wir bearbeiten das xsl:elsif und xslx:else in einem speziellen Modus als Teil von xsl:choose. Wir müssen sicherstellen, nur die zu nehmen, deren vorausgehendes xslx:if dieses xslx:if ist -->
      <xsl:apply-templates select="following-sibling::xslx:else[generate-id(preceding-sibling::xslx:if[1]) = $idIf] | following-sibling::xslx:elsif[generate-id(preceding-sibling::xslx:if[1]) = $idIf]" mode="choose"/>
    </xso:choose>
  </xsl:template>
  <!-- Ignoriere xslx:elsif und xslx:else im normalen Modus -->
  <xsl:template match="xslx:elsif | xslx:else"/>
  <!-- Ein xslx:elsif wird zu xsl:when -->
  <xsl:template match="xslx:elsif"  mode="choose">
    <xso:when test="{@test}">
      <xsl:apply-templates select="@* | node( )"/>
    </xso:when>
  </xsl:template>
  <!-- Ein xslx:else wird zu xsl:otherwise -->
  <xsl:template match="xslx:else" mode="choose">
    <xso:otherwise>
      <xsl:apply-templates/>
    </xso:otherwise>
  </xsl:template>
  <!-- Ein xslx:loop wird zum Aufruf eines benannten Templates -->
  <xsl:template match="xslx:loop">
    <!-- Jedes Template erhält den Namen loop-N, wobei N die Position dieser Schleife relativ zu vorherigen Schleifen beliebiger Tiefe ist. -->
    <xsl:variable name="name">
      <xsl:text>loop-</xsl:text>
      <xsl:number count="xslx:loop" level="any"/>
    </xsl:variable>
    <xso:call-template name="{$name}">
      <xsl:for-each select="ancestor::xslx:loop">
        <xso:with-param name="{@param}" select="${@param}"/>
      </xsl:for-each>
      <xso:with-param name="{@param}" select="{@init}"/>
    </xso:call-template>
  </xsl:template>
  <!-- Der Modus loop-body wird im zweiten Durchgang benutzt. -->
  <!-- Hier werden rekursive Templates für die Schleifen generiert. -->
  <xsl:template match="xslx:loop" mode="loop-body">
    <xsl:variable name="name">
      <xsl:text>loop-</xsl:text>
      <xsl:value-of select="position( )"/>
    </xsl:variable>
    <xso:template name="{$name}">
      <!-- Falls diese Schleife in einer anderen verschachtelt ist, muss sie die äußeren Schleifenparameter "sehen", daher generieren wir diese hier. -->
      <xsl:for-each select="ancestor::xslx:loop">
        <xso:param name="{@param}"/>
      </xsl:for-each>
      <!-- Der lokale Schleifenparameter -->
      <xso:param name="{@param}"/>
      <!-- Generiere den Rekursionssteuerungstest -->
      <xso:if test="{@test}">
        <!-- Wende Template im normalen Modus an, um Aufrufe von verschachtelten Schleifen zu behandeln, während alles andere kopiert wird. -->
        <xsl:apply-templates/>
        <!-- Das ist der rekursive Aufruf, der das incr auf den Schleifenparameter anwendet -->
        <xso:call-template name="{$name}">
          <xsl:for-each select="ancestor::xslx:loop">
            <xso:with-param name="{@param}" select="${@param}"/>
          </xsl:for-each>
          <xso:with-param name="{@param}" select="${@param} + {@incr}"/>
        </xso:call-template>
      </xso:if>
    </xso:template>
  </xsl:template>
</xsl:stylesheet>

The generated result is:

<xso:stylesheet xmlns:xso="http://www.w3.org/1999/XSL/Transform" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xslx="http://www.ora.com/XSLTCookbook/ExtendedXSLT" version="1.0">
  <xsl:output method="text"/>
  <xsl:template match="foo">
    <xso:choose>
      <xso:when test="bar">
        <xsl:text>In der Nähe von foo werden Sie oft eine bar finden!</xsl:text>
      </xso:when>
      <xso:when test="baz">
        <xsl:text>Ein baz ist ein sicheres Zeichen von Besessenheit.</xsl:text>
      </xso:when>
      <xso:otherwise>
        <xso:call-template name="loop-1">
          <xso:with-param name="i" select="0"/>
        </xso:call-template>
      </xso:otherwise>
    </xso:choose>
    <xso:call-template name="loop-2">
      <xso:with-param name="i" select="10"/>
    </xso:call-template>
    <xso:choose>
      <xso:when test="foo">
        <xsl:text>foo foo! Niemand sagt foo foo!</xsl:text>
      </xso:when>
      <xso:otherwise>
        <xsl:text>Na ja, also gut!</xsl:text>
      </xso:otherwise>
    </xso:choose>
  </xsl:template>
  <xso:template name="loop-1">
    <xso:param name="i"/>
    <xso:if test="$i &lt; 10">
      <xsl:text>Hmm, ich habe nichts zu sagen, aber das 10-mal.</xsl:text>
      <xso:call-template name="loop-1">
        <xso:with-param name="i" select="$i + 1"/>
      </xso:call-template>
    </xso:if>
  </xso:template>
  <xso:template name="loop-2">
    <xso:param name="i"/>
    <xso:if test="$i &gt;= 0">
      <xso:call-template name="loop-3">
        <xso:with-param name="i" select="$i"/>
        <xso:with-param name="j" select="10"/>
      </xso:call-template>
      <xso:call-template name="loop-2">
        <xso:with-param name="i" select="$i + −1"/>
      </xso:call-template>
    </xso:if>
  </xso:template>
  <xso:template name="loop-3">
    <xso:param name="i"/>
    <xso:param name="j"/>
    <xso:if test="$j &gt;= 0">
      <xsl:text></xsl:text>
      <xsl:value-of select="$i * $j"/>
      <xso:call-template name="loop-3">
        <xso:with-param name="i" select="$i"/>
        <xso:with-param name="j" select="$j + −1"/>
      </xso:call-template>
    </xso:if>
  </xso:template>
</xso:stylesheet>

Discussion

The key to generating XSLT with XSLT is element xsl:namespace-alias. Without it, the processor could not distinguish real XSLT from content output literally. This technique has many uses beyond the example, including:

Supporting literate programming

In literate programming, code fragments are embedded in human-readable documentation rather than the reverse. Information follows the order best for people, not compilers.

Conditional includes and imports

Adding this to XSLT would probably need difficult processing-model extensions, like a C preprocessor.

Dynamic XPath evaluation

A stylesheet generates XPath expressions from an imported source and embeds them in another stylesheet for static evaluation. This extra step emulates dynamic behavior. Often the expressions are embedded in a document, such as this table specification:

<table of="person">
  <column label="Firstname" content="name/firstname" />
  <column label="Surname" content="name/surname" />
  <column label="Age" content="@age" type="number" />
  <sort select="Surname, Firstname, Age" />
</table>

Generating XSLT from this table specification and running it over the data is easier than interpreting the specification in the stylesheet processing the data.

See also

For a similar example with validation, see Oliver Becker’s XSLT-Loop Compiler.

  

 

 

 

back to top