Set a variable to the smaller of the other two variables
When I try to use the code below, I get a duplicate variable because the variables are immutable. How to set the smaller of the two variables ( $nextSubPartPos
and $nextQuestionStemPos
) as my new variable ( $nextQuestionPos
)?
<xsl:variable name="nextQuestionPos"/>
<xsl:choose>
<xsl:when test="$nextSubPartPos < $nextQuestionStemPos">
<xsl:variable name="nextQuestionPos" select="$nextSubPartPos"/>
</xsl:when>
<xsl:otherwise>
<xsl:variable name="nextQuestionPos" select="$nextSubPartPos"/>
</xsl:otherwise>
</xsl:choose>
source to share
Don't cover the xsl: variable node on the first line. That is, take / from it, then put </xsl:variable>
after </xsl:choose>
. Then change the nodes <xsl:variable>
inside the selection nodes <xsl:value-of>
.
That is, you want to set the value of a variable with. There are two ways to set the value of a variable. One is the select attribute, the other is the inner text of the node.
<xsl:variable name="nextQuestionPos">
<xsl:choose>
<xsl:when test="$nextSubPartPos < $nextQuestionStemPos">
<xsl:value-of select="$nextSubPartPos"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$nextSubPartPos"/>
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
source to share
A compact XPath 1.0 expression that evaluates to a smaller value is:
$ v1 * ($ v2> = $ v1) + $ v2 * ($ v1> $ v2)
where the variables $ v1 and $ v2 contain the values ββto compare.
So an elegant one-line XSLT 1.0 solution would look like this:
<xsl: variable name = "v3" select = "$ v1 * ($ v2> = $ v1) + $ v2 * ($ v1> $ v2)" / ">
It is easier to define a variable as required in XSLT 2.0:
Either the following (more readable) one-liner can be used:
if ($ v2 gt $ v1)
else $ v2
Or more compact:
min (($ v1, $ v2))
source to share
Just use the function min
:
<xsl:variable name="a" select="42" />
<xsl:variable name="b" select="23" />
<xsl:variable name="x" select="min(($a,$b))" />
In your example, replace all your code with:
<xsl:variable name="nextQuestionPos" select="min(($nextSubPartPos,$nextQuestionStemPos))" />
Saxon implements min in the global namespace. Other processors may require a namespace, the correct (usually denoted fn
) is http://www.w3.org/2005/02/xpath-functions
.
source to share