Function to raise to power in XSLT

By xngo on February 21, 2019

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="text" encoding="UTF-8" />
 
  <!-- Usage example: Calculate 10^5-->
  <xsl:template match="*">
    <xsl:param name="PowResult">
      <xsl:call-template name="Pow">
        <xsl:with-param name="Base" select="10"/>
        <xsl:with-param name="Exponent" select="5"/>
        <xsl:with-param name="Result" select="1"/><!-- Always set to 1 when Pow() function is used. -->
      </xsl:call-template>
    </xsl:param>
    <xsl:value-of select="$PowResult"/><!-- Display the result -->
  </xsl:template>
 
  <!-- Generic function: Pow($Base, $Exponent)-->
  <!-- Multiple $Base $Exponent time recursively until $Exponent is equal to 0. -->
  <xsl:template name="Pow">
    <xsl:param name="Base"/>
    <xsl:param name="Exponent"/>
    <xsl:param name="Result"/>
    <xsl:choose>
      <xsl:when test="$Exponent = 0">
        <xsl:value-of select="1"/>
      </xsl:when>
      <xsl:when test="$Exponent = 1">
        <xsl:value-of select="$Result * $Base"/>
      </xsl:when>
      <xsl:otherwise>
        <xsl:call-template name="Pow">
          <xsl:with-param name="Base" select="$Base"/>
          <xsl:with-param name="Exponent" select="$Exponent - 1"/>
          <xsl:with-param name="Result" select="$Result * $Base"/>
        </xsl:call-template>                          
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>
 
</xsl:stylesheet>

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.