Elemento <xsl:choose> XSLT
- Pagina precedente XSLT <if>
- Pagina successiva XSLT Apply
L'elemento <xsl:choose> di XSLT viene utilizzato per combinare <xsl:when> e <xsl:otherwise> per esprimere test condizionali multipli.
<xsl:choose> elemento
Sintassi
<xsl:choose> <xsl:when test="espressione"> ... Output ... </xsl:when> <xsl:otherwise> ... Output ... </xsl:otherwise> </xsl:choose>
Dove posizionare le condizioni di selezione
Per inserire test condizionali multipli per un file XML, aggiungi <xsl:choose>, <xsl:when> e <xsl:otherwise> al file XSL:
<?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" <xsl:template match="/"> <html> <body> <h2>My 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:stylesheet>
Il codice sopra aggiungerà un colore di sfondo rosa alla colonna "Artist" quando il prezzo del CD è superiore a 10.
Il risultato della conversione è simile a questo:

Visualizza questo file XML,Visualizza questo file XSL,Visualizza i risultati.
Un altro esempio
Esempio di un altro contenente due elementi <xsl:when>:
<?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" <xsl:template match="/"> <html> <body> <h2>My 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:stylesheet>
Il codice aggiungerà lo sfondo rosa alla colonna "Artist" quando il prezzo del CD è superiore a 10, e aggiungerà lo sfondo grigio alla colonna "Artist" quando il prezzo del CD è superiore a 9 e inferiore o uguale a 10.
Il risultato della conversione è simile a questo:

Visualizza questo file XML,Visualizza questo file XSL,Visualizza i risultati.
- Pagina precedente XSLT <if>
- Pagina successiva XSLT Apply