Is it possible to implement "if else, if else" in xsl? for example I have data:
<document> <line> <name>MAR111</name> <value>1</value> </line> <line> <name>MAR111</name> <value>3</value> </line> <line> <name>MEA111</name> <value>1</value> </line> <line> <name>MPR111</name> <value>1</value> </line> <line> <name>MEA111</name> <value>4</value> </line> <line> <name>MPR111</name> <value>2</value> </line> </document>
I need to get three document templates with three names:
<document> <MAR> <name>MAR111</name> <number>1</number> <number>4</number> </MAR> </document> <document> <MEA> <name>MEA111</name> <number>1</number> <number>4</number> </MEA> </document> <document> <MPR> <name>MPR111</name> <number>1</number> <number>2</number> </MPR> </document>
I try to use "choose, when" on apply template, but maybe there is a better way:
<xsl:template match="/"> <xsl:choose> <xsl:when test="/document/line/name='MEA111'"> <xsl:apply-templates mode="MEA" select="/document"/> </xsl:when> </xsl:choose> <xsl:choose> <xsl:when test="/document/line/name='MPR111'"> <xsl:apply-templates mode="MPR" select="/document"/> </xsl:when> </xsl:choose> <xsl:choose> <xsl:when test="/document/line/name='MAR111'"> <xsl:apply-templates mode="MAR" select="/document"/> </xsl:when> </xsl:choose> </xsl:template>
XSL specifications implies a function<xsl: choose> to implement the functionality of if-else statements. To work with multiple options, we are supposed to use <choose> along with <otherwise> which is equivalent to anything else. The attribute is evaluated until the processor finds the condition that is met true.
The <xsl:if> Element To put a conditional if test against the content of the XML file, add an <xsl:if> element to the XSL document.
Yes we can have multiple conditions in the same <xsl:when> element.
The XSLT <xsl:if> element is used to specify a conditional test against the content of the XML file.
Actually you can merge them together:
<xsl:template match="/"> <xsl:choose> <xsl:when test="/document/line/name='MEA111'"> <xsl:apply-templates mode="MEA" select="/document"/> </xsl:when> <xsl:when test="/document/line/name='MPR111'"> <xsl:apply-templates mode="MPR" select="/document"/> </xsl:when> <xsl:when test="/document/line/name='MAR111'"> <xsl:apply-templates mode="MAR" select="/document"/> </xsl:when> </xsl:choose> </xsl:template>
EDIT: Petras, after your clarification, it seems that what you want is even easier:
<xsl:template match="/"> <xsl:if test="/document/line/name='MEA111'"> <xsl:apply-templates mode="MEA" select="/document"/> </xsl:if> <xsl:if test="/document/line/name='MPR111'"> <xsl:apply-templates mode="MPR" select="/document"/> </xsl:if> <xsl:if test="/document/line/name='MAR111'"> <xsl:apply-templates mode="MAR" select="/document"/> </xsl:if> </xsl:template>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With