I needed a function for a XSLT that will trim a string. Here it is.
First you got an example of how to use the function.
<Cancel>
<xsl:call-template name="trimString">
<xsl:with-param name="s" select="./CANCEL"/>
</xsl:call-template>
</Cancel>
And here is the trim function.
<!-- Template for trimming strings -->
<!-- Left Trim -->
<xsl:template name="leftTrim">
<xsl:param name="inParam"/>
<xsl:choose>
<xsl:when test="substring($inParam, 1, 1) = ''">
<xsl:value-of select="$inParam"/>
</xsl:when>
<xsl:when test="normalize-space(substring($inParam, 1, 1)) = ''">
<xsl:call-template name="leftTrim">
<xsl:with-param name="inParam" select="substring($inParam, 2)"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$inParam"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<!-- Right Trim -->
<xsl:template name="rightTrim">
<xsl:param name="inParam"/>
<xsl:choose>
<xsl:when test="substring($inParam, 1, 1) = ''">
<xsl:value-of select="$inParam"/>
</xsl:when>
<xsl:when test="normalize-space(substring($inParam, string-length($inParam))) = ''">
<xsl:call-template name="rightTrim">
<xsl:with-param name="inParam" select="substring($inParam, 1, string-length($inParam) - 1)"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$inParam"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<!-- Trim by using right and left trim -->
<xsl:template name="trimString">
<xsl:param name="inParam"/>
<xsl:call-template name="rightTrim">
<xsl:with-param name="inParam">
<xsl:call-template name="leftTrim">
<xsl:with-param name="inParam" select="$inParam"/>
</xsl:call-template>
</xsl:with-param>
</xsl:call-template>
</xsl:template>
Friday, July 6, 2007
Subscribe to:
Post Comments (Atom)
1 comment:
thanks Johan - your example is slick, recusion makes sense here, and I finally grasp the mechanics of using xsl:call-template versus xsl:apply-templates. Much appreciated.
Post a Comment