The xml document below represents 3 number, 2, 2 and 2. A node <s> is counted as a number and ended with <zero/>.
<?xml version="1.0" encoding="UTF-8"?>
<nat xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="nat.xsd">
<s>
<s>
<zero/>
</s>
</s>
<s>
<s>
<zero/>
</s>
</s>
<s>
<s>
<zero/>
</s>
</s>
</nat>
I just started learning with xslt and this is one of the exercise for recursion. I could do plus recursively for adding up all numbers but this multiplying more than two number just blows my mind. I have no idea how to do it.
The expected answer for above xml doc is 8s(ignore the format) :
<s><s><s><s><s><s><s><s><zero/></s></s></s></s></s></s></s></s>
My idea was this, I can have a template to do multiplication for two number by adding. So for this 2x2x2, I would do the 2nd 2 times the 3rd 2 that returns 4 and finally do 2*4. But call template don’t return value in xslt unlike java or scheme so I appreciate any hints/helps.
Update:
I got my answer by adding in a print template to Dimitre’s answer. Here it is:
<xsl:template name="print">
<xsl:param name="pAccum"/>
<xsl:choose>
<xsl:when test="$pAccum > 0">
<s>
<xsl:call-template name="print">
<xsl:with-param name="pAccum" select="$pAccum - 1"/>
</xsl:call-template>
</s>
</xsl:when>
<xsl:otherwise>
<zero/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
This transformation:
when applied on the provided XML document:
produces the wanted, correct result:
Explanation:
Primitive recursion with stop condition — empty argument node-set and an accumulator – parameter for passing the currently accumulated result to the next recursive call.