Useful XSLT snippet with translate()

Let’s say there is a following function written in XSLT 2.0:

    <xsl:function name="str:convertBits">
        <xsl:param name="cpnNumber" />

        <xsl:choose>
            <xsl:when test="$cpnNumber = 1">
                <xsl:value-of>8</xsl:value-of>
            </xsl:when>
            <xsl:when test="$cpnNumber = 2">
                <xsl:value-of>4</xsl:value-of>
            </xsl:when>
            <xsl:when test="$cpnNumber = 3">
                <xsl:value-of>2</xsl:value-of>
            </xsl:when>
            <xsl:when test="$cpnNumber = 4">
               <xsl:value-of>1</xsl:value-of>
            </xsl:when>
            <xsl:otherwise>
               <xsl:value-of>0</xsl:value-of>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:function>

Quite long, isn’t it?

This is how it can be shortened:

number(translate(xs:string($cpnNumbers[1]), '1234567890', '8421000000'))

2 thoughts on “Useful XSLT snippet with translate()

Comments are closed.