choose_1-input.xml
<?xml version="1.0"?>
<products>
<product
id="p1" stock="4"/>
</products>
choose_1-stylesheet.xsl
<?xml version="1.0"?>
<xsl:stylesheet
version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:variable
name="x" select="products/product"/>
<xsl:output
indent="yes"/>
<xsl:template
match="/">
<Products>
<Product>
<xsl:attribute
name="id" select="$x/@id"/>
<xsl:choose>
<xsl:when
test="not($x/@stock)">
<xsl:message
terminate="yes">Stock attribute is missing.</xsl:message>
</xsl:when>
<xsl:when
test="not(number($x/@stock))">
<xsl:message
terminate="yes">Value of stock must be a number.</xsl:message>
</xsl:when>
<xsl:when
test="$x/@stock < 0">
<xsl:message
terminate="yes">Value of stock must be >= 0.</xsl:message>
</xsl:when>
<xsl:otherwise>
<xsl:attribute
name="stock" select="$x/@stock"/>
</xsl:otherwise>
</xsl:choose>
</Product>
</Products>
</xsl:template>
</xsl:stylesheet>
choose_1-output.xml
<?xml version="1.0" encoding="UTF-8"?>
<products>
<product
id="p1" stock="4"/>
</products>
At least one xsl:when must be child of xsl:choose. The order of xsl:when and the tests must be done carefully: as soon as a test is negative the switch has found its way.
Updated 2009-03-19