Reputation: 2241
Got this XML file:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="equipos.xsl"?>
<equipos>
<equipo nombre="Los paellas" personas="2"/>
<equipo nombre="Los arrocitos" personas="13"/>
<equipo nombre="Los gambas" personas="6"/>
<equipo nombre="Los mejillones" personas="3"/>
<equipo nombre="Los garrofones" personas="17"/>
<equipo nombre="Los limones" personas="7"/>
</equipos>
Applying an XSLT the output must be:
This is my XSLT for now, but i dont find the way to get the 3rd condition for "categoria" on choose...
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="equipos">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="equipo">
<xsl:copy>
<xsl:attribute name="nombre">
<xsl:value-of select="@nombre"/>
</xsl:attribute>
<xsl:attribute name="categoria">
<xsl:choose>
<xsl:when test="@personas < 5">
<xsl:text>1</xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:text>2</xsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:attribute>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Upvotes: 0
Views: 645
Reputation: 122414
You can have as many when
elements as you like inside the choose
:
<xsl:choose>
<xsl:when test="@personas < 5">
<xsl:text>1</xsl:text>
</xsl:when>
<xsl:when test="@personas <= 10">
<xsl:text>2</xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:text>3</xsl:text>
</xsl:otherwise>
</xsl:choose>
A choose
takes the first matching when
branch, so you don't need to check for >=5
in the second branch - you already know this because you didn't take the first one.
But for future reference, a more idiomatic XSLT way to approach this might be to use matching templates instead of a choose
construct:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<!-- copy everything unchanged except when overridden -->
<xsl:template match="@*|node()">
<xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
</xsl:template>
<xsl:template match="@personas[. < 5]" priority="10">
<xsl:attribute name="categoria">1</xsl:attribute>
</xsl:template>
<xsl:template match="@personas[. <= 10]" priority="9">
<xsl:attribute name="categoria">2</xsl:attribute>
</xsl:template>
<xsl:template match="@personas" priority="8">
<xsl:attribute name="categoria">3</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
Here we need the explicit priorities because the patterns @personas[. < 5]
and @personas[. <= 10]
are considered equally specific by default.
Upvotes: 2