Tuesday, July 04, 2006

XSLT Replace Template

I was working on a site today that required me to split a string in the form of a=1;b=2;c=3 in xsl. Now xsl does provide a translate() function but it doesn't traverse the whole string doing a normal replacement as you might expect. Instead a trawled the internet and found the following little template which nicely recurses through and does the replacement. I thought I'd post it here so I can find it again - and share it with the world of course!

  <xsl:template name="replace">

    <xsl:param name="string" select="." />


      <xsl:when test="not($string)" />

      <xsl:when test="contains($string, ';')">

        <xsl:value-of select="substring-before($string, ';')" />

        <br />

        <xsl:call-template name="replace">

          <xsl:with-param name="string" select="substring-after($string, ';')" />




        <xsl:value-of select="$string" />

        <br />





All you need do is call the template and pass your input into with $string param, in my case this was the ";". Then replace the <br/> tags with whatever you need to replace your input string with - easy!

Post a Comment