Friday, 14 December 2007

XSLT replace - the code

Extending on my post earlier today - thought I may as well include the code:

<?xml version="1.0" ?>
<xsl:stylesheet xmlns:xsl=" " version="1.0">

<!-- reusable replace-string function -->
<xsl:template name="replace-string">
<xsl:param name="text"/>
<xsl:param name="from"/>
<xsl:param name="to"/>
<xsl:when test="contains($text, $from)">
<xsl:variable name="before" select="substring-before($text, $from)"/>
<xsl:variable name="after" select=" substring-after($text, $from)"/>
<xsl:variable name="prefix" select="concat($before, $to)"/>
< xsl:value-of select="$before"/>
< xsl:value-of select="$to"/>
< xsl:call-template name="replace-string">
<xsl:with-param name="text" select="$after"/>
<xsl:with-param name="from" select="$from"/>
<xsl:with-param name="to" select="$to"/>
<xsl:value-of select="$text"/>
</ xsl:otherwise>

<!-- test the function -->
<xsl:template match="/">
<xsl:call-template name="replace-string">
<xsl:with-param name="text"
select="'Mary had a little lamb, little lamb, little lamb.'"/>
<xsl:with-param name="from" select="'little lamb'"/>
<xsl:with-param name="to" select="'little steak'"/>
Will make life a bit easier if I ever come to use this code again ;-)

No comments:

Post a Comment

Migrating (and Open-Sourcing) an Historical Codebase: SVN-to-Git

I have a SVN repo on my local machine that I have been shoving stuff into since before I knew how to use revision control systems properly (...