XSLT <xsl:when>Elemento
Referencia completa de elementos XSLT
Definición y uso
El elemento <xsl:when> se utiliza para especificar una acción relacionada para el elemento <xsl:choose>. El elemento <xsl:when> evalúa una expresión y, si devuelve true, ejecuta la acción especificada.
Nota:El elemento <xsl:when> se usa junto con <xsl:choose> y <xsl:otherwise> para expresar múltiples pruebas condicionales.
Sintaxis
<xsl:when
test="boolean-expression">
<!-- Content: template -->
</xsl:when>
test="boolean-expression">
<!-- Content: template -->
</xsl:when>
Atributos
| Atributo | Valor | Descripción |
|---|---|---|
| test | boolean-expression | Obligatorio. Especifica la expresión booleana que se va a evaluar. |
Ejemplo 1
El siguiente código agregará un color de fondo rosa a la columna artist cuando el precio de cd sea superior a 10.
<?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>
<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>
、 、 。
Ejemplo 2
Se declara una variable llamada "color". Su valor se asigna al atributo color del elemento actual. Si el elemento actual no tiene el atributo color, el valor de "color" será "green":
<xsl:variable name="color">
<xsl:choose>
<xsl:when test="@color">
<xsl:value-of select="@color"/>
</xsl:when>
<xsl:otherwise>green</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<xsl:choose>
<xsl:when test="@color">
<xsl:value-of select="@color"/>
</xsl:when>
<xsl:otherwise>green</xsl:otherwise>
</xsl:choose>
</xsl:variable>
Referencia completa de elementos XSLT Otras extensiones