Search code examples
xsltxsl-choosexsl-variable

Using xsl:variable to set another variable using xsl:choose -> Invalid property


I'm trying to define some standard colours to use elsewhere in an XSLT, but the following gives an error:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" version="2.0">

    <xsl:variable name="rgbWeiss"       >rgb(255, 255, 255)</xsl:variable>
    <xsl:variable name="rgbHellBlauGrau">rgb(213, 235, 229)</xsl:variable>
    <xsl:variable name="rgbDunkelRot"   >rgb(128,   0,   0)</xsl:variable>
    :
    :
    <xsl:template match="row">

        <xsl:variable name="bgcolor">
            <xsl:choose>
                <xsl:when      test="position() mod 2 = 1">rgb(213, 235, 229)</xsl:when>
                <xsl:otherwise                            >${rgbDunkelRot}</xsl:otherwise>
            </xsl:choose>
        </xsl:variable>

        <fo:table-row background-color="{$bgcolor}" xsl:use-attribute-sets="table-row-attr">

The error message is:

Invalid property value encountered in background-color="${rgbDunkelRot}"

Unfortunately no useful information was provided for the location of the error.

The following works fine though:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" version="2.0">
    :
    :
    <xsl:template match="row">

        <xsl:variable name="bgcolor">
            <xsl:choose>
                <xsl:when      test="position() mod 2 = 1">rgb(213, 235, 229)</xsl:when>
                <xsl:otherwise                            >rgb(128,   0,   0)</xsl:otherwise>
            </xsl:choose>
        </xsl:variable>

        <fo:table-row background-color="{$bgcolor}" xsl:use-attribute-sets="table-row-attr">

Any ideas?


Solution

  • With XSLT 2 (you seem to use) I would simply do

    <fo:table-row background-color="{if (position() mod 2 = 1) then $rgbHellBlauGrau else $rgbDunkelRot}" xsl:use-attribute-sets="table-row-attr">
    

    or use that expression in the variable

    <xsl:variable name="bgcolor" select="if (position() mod 2 = 1) then $rgbHellBlauGrau else $rgbDunkelRot"/>
    

    Inside of the xsl:choose/xsl:when/xsl:otherwise you have the wrong syntax, you need <xsl:otherwise><xsl:value-of select="$rgbDunkelRot"/></xsl:otherwise> or move to XSLT 3 and expand-text="yes" with e.g. <xsl:otherwise>{$rgbDunkelRot}</xsl:otherwise>.

    In "XSLT 4" currently experimented with in Saxon 10 PE or EE as an extension there is also a select attribute on xsl:when and xsl:otherwise: http://saxonica.com/html/documentation/extensions/xslt-syntax-extensions.html. So there you can write <xsl:when test="position() mod 2 = 1" select="$rgbHellBlauGrau"/>.