0">

XSL Basics: Mapping a Boolean Value?

When I have it in xsl:

<xsl:choose> <xsl:when test="something > 0"> <xsl:variable name="myVar" select="true()"/> </xsl:when> <xsl:otherwise> <xsl:variable name="myVar" select="false()"/> </xsl:otherwise> </xsl:choose> 

How can I print the value of "myVar"? Or, more importantly, how can I use this boolean in another select clause?

+4
source share
1 answer
 <xsl:choose> <xsl:when test="something > 0"> <xsl:variable name="myVar" select="true()"/> </xsl:when> <xsl:otherwise> <xsl:variable name="myVar" select="false()"/> </xsl:otherwise> </xsl:choose> 

This is completely wrong and useless because the $myVar variable is out of scope .

One correct way to conditionally assign a variable:

 <xsl:variable name="myVar"> <xsl:choose> <xsl:when test="something > 0">1</xsl:when> <xsl:otherwise>0</xsl:otherwise> </xsl:choose> </xsl:variable> 

However, you really do not need this - much simpler :

 <xsl:variable name="myVar" select="something > 0"/> 
 How can I then print out the value of "myVar"? 

Using

 <xsl:value-of select="$myVar"/> 

Or, more importantly, how can I use this boolean in another statement?

Here is a simple example:

 <xsl:choose> <xsl:when test="$myVar"> <!-- Do something --> </xsl:when> <xsl:otherwise> <!-- Do something else --> </xsl:otherwise> </xsl:choose> 

And here is a complete example :

 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:template match="/*/*"> <xsl:variable name="vNonNegative" select=". >= 0"/> <xsl:value-of select="name()"/>: <xsl:text/> <xsl:choose> <xsl:when test="$vNonNegative">Above zero</xsl:when> <xsl:otherwise>Below zero</xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet> 

when this conversion is applied to the following XML document :

 <temps> <Monday>-2</Monday> <Tuesday>3</Tuesday> </temps> 

required, the correct result is obtained :

  Monday: Below zero Tuesday: Above zero 
+7
source

Source: https://habr.com/ru/post/1398658/


All Articles