XSLT xsl:choose Element
xsl:choose The element is used together with xsl:when and xsl:otherwise to express multiple conditional tests.
xsl:choose Element
Syntax
... some output ...
... some output ....
Where to place the selection condition
To insert multiple conditional tests for an XML file, add the xsl:choose、xsl:when and xsl:otherwise element:
Example
<
xsl:stylesheet
version
=
"
1.0
"
xmlns:xsl
=
"
http://www.w3.org/1999/XSL/Transform
"
<
xsl:template
match
=
"
/
"
<
html
<
body
<
h2My CD Collection
h2
<
table
border
=
"
1
"
<
tr
bgcolor
=
"
#9acd32
"
<
th
Title
th
<
th
Artist
th
tr
<
xsl:for-each
select
=
"
catalog/cd
"
<
tr
<
td
<
xsl:value-of
select
=
"
title
"
/>
td
<
xsl:choose
<
xsl:when
test
=
"
price
>
10
"
<
td
bgcolor
=
"
#ff00ff
"
<
xsl:value-of
select
=
"
artist
"
/>
td
xsl:when
<
xsl:otherwise
<
td
<
xsl:value-of
select
=
"
artist
"
/>
td
xsl:otherwise
xsl:choose
tr
xsl:for-each
table
body
html
xsl:template
xsl:stylesheetTry it »
The code above adds a pink background color to the "Artist" column when the price of a CD is greater than 10.
Another example
This is another example containing two xsl:when elements:
Example
<
xsl:stylesheet
version
=
"
1.0
"
xmlns:xsl
=
"
http://www.w3.org/1999/XSL/Transform
"
<
xsl:template
match
=
"
/
"
<
html
<
body
<
h2My CD Collection
h2
<
table
border
=
"
1
"
<
tr
bgcolor
=
"
#9acd32
"
<
th
Title
th
<
th
Artist
th
tr
<
xsl:for-each
select
=
"
catalog/cd
"
<
tr
<
td
<
xsl:value-of
select
=
"
title
"
/>
td
<
xsl:choose
<
xsl:when
test
=
"
price
>
10
"
<
td
bgcolor
=
"
#ff00ff
"
<
xsl:value-of
select
=
"
artist
"
/>
td
xsl:when
<
xsl:when
test
=
"
price
>
9
"
<
td
bgcolor
=
"
#cccccc
"
<
xsl:value-of
select
=
"
artist
"
/>
td
xsl:when
<
xsl:otherwise
<
td
<
xsl:value-of
select
=
"
artist
"
/>
td
xsl:otherwise
xsl:choose
tr
xsl:for-each
table
body
html
xsl:template
xsl:stylesheetTry it »
The code above adds a pink background color to the "Artist" column when the price of a CD is greater than 10, and a gray background color to the "Artist" column when the price of a CD is greater than 9 and less than or equal to 10.