I'm a novice in XSLT and I'm struggling a lot with this issue: I need to do a while-like loop in XSLT. I don't think the for-each will be enough to solve this problem.
I have a variable that is the result of a SELECT statement. It can return 0 or an integer. If the value is 0, it needs to do the SELECT again sending another parameter to see if the value is different.
I can only think in using a while-like loop, but maybe it has another way of achieving this? Like using a template and calling itself in the end? Is it possible?
Something like that:
<!-- initiate TEMPLATE -->
<!-- WHILE $VALUE = 0 -->
<xsl:variable name="sql.query">
<sql:param name="SQL_QUERY">SELECT $value FROM date_table WHERE date='$date'</mx:param>
</xsl:variable>
<xsl:variable name="VALUE">
<xsl:value-of select="sql:exec-formula('generic.sql', exsl:node-set($sql.query)//sql:param)" /> <!-- this will bring the result of the SELECT in the variable -->
</xsl:variable>
<xsl:variable name="date">
<xsl:value-of select="$date-1" /> <!-- something like that, it doesn't matter -->
</xsl:variable>
<xsl:if test="$VALUE ='0'">
<!-- call template again -->
</xsl:if>
<!-- end of template -->
<!-- recursive named template -->
<xsl:template name="while">
<xsl:variable name="VALUE">
<!-- your evaluation -->
</xsl:variable>
<!-- evaluate and recurse -->
<xsl:if test="$VALUE=0">
<xsl:call-template name="while"/>
</xsl:if>
</xsl:template>
Like using a template and calling itself in the end?
Correct: tail recursion is the usual solution to this problem, as illustrated by empo. The better XSLT processors will optimize tail recursion so it doesn't comsume the stack. The worse ones will run out of stack space after 500 or so iterations, in which case you need to look for a different solution.
Note: try to avoid this kind of construct
<xsl:variable name="date">
<xsl:value-of select="$date - 1" />
</xsl:variable>
when you could do
<xsl:variable name="date" select="$date - 1" />
It's unnecessarily verbose, and can also be very inefficient because the variable value is a tree rather than a simple string or number.
来源:https://stackoverflow.com/questions/11127693/how-to-do-a-while-like-loop-in-xslt