Is it possible to implement \"if else, if else\" in xsl? for example I have data:
MAR111
Do you mean something like:
<xsl:choose>
<xsl:when test="name() = 'MAR111'">
... do something ...
</xsl:when>
<xsl:otherwise>
... do something as fallback ...
</xsl:otherwise>
</xsl:choose>
BR Markus
This stylesheet:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:key name="kLineByName" match="line" use="name"/>
<xsl:template match="line[count(.|key('kLineByName',name)[1]) = 1]">
<document>
<xsl:element name="{substring(name,1,3)}">
<xsl:copy-of select="name|key('kLineByName',name)/value"/>
</xsl:element>
</document>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
Output:
<document>
<MAR>
<name>MAR111</name>
<value>1</value>
<value>3</value>
</MAR>
</document>
<document>
<MEA>
<name>MEA111</name>
<value>1</value>
<value>4</value>
</MEA>
</document>
<document>
<MPR>
<name>MPR111</name>
<value>1</value>
<value>2</value>
</MPR>
</document>
The best way is to use separate templates.
<xsl:template match="/document/line/name='MEA111'">
<xsl:apply-templates mode="MEA" select="/document"/>
</xsl:template>
<xsl:template match="/document/line/name='MPR111'">
<xsl:apply-templates mode="MPR" select="/document"/>
</xsl:template>
<xsl:template match="/document/line/name='MAR111'">
<xsl:apply-templates mode="MAR" select="/document"/>
</xsl:template>
Even less lines and this is more maintainable.
Yes, we can achieve things using <xsl:choose><xsl:when>
but if, else if, condition is also supported in @select attribute of different xslt construct for example :
<xsl:value-of select="if (@geography = 'North America') then
'Domestic car'
else if (@geography = 'Europe') then
'Import from Europe'
else if (@geography = 'Asia') then
"It's from Asia"
(: If it's anything else :)
else
'We don''t know!'"/>
No, choose when
is the xsl way of saying if else
. No better way
if you want to implement a catch-all fall through (e.g. equivalent to "else"), you should use otherwise