Archive

Archive for July, 2009

Replace function for xsl

July 17th, 2009 4 comments

If you are using xsl 1.0, you will face small things missing from the functions set. String manipulation is very common and you need in every programming and scripting language. In xsl 1.0 most of the functions are missing. Today I’m going to give you idea that how can we create and use Replace function for strings.

<xsl:template name=string-replace>
   <
xsl:param name=text />
   <
xsl:param name=pattern />
   <
xsl:param name=replace-with />
  
<xsl:choose>
      <
xsl:when test=contains($text, $pattern)>
         <
xsl:value-of select=substring-before($text, $pattern) />
         <
xsl:value-of select=$replace-with />
         <
xsl:call-template name=string-replace>
            <
xsl:with-param name=text select=substring-after($text, $pattern) />
            <
xsl:with-param name=pattern select=$pattern />
            <
xsl:with-param name=replace-with select=$replace-with />
         </
xsl:call-template>
      </
xsl:when>
      <
xsl:otherwise>
         <
xsl:value-of select=$text />
      </
xsl:otherwise>
   </
xsl:choose>
</
xsl:template>

Here how to use this string-replace function. Here I’m creating a variable name MYTextReplaced, and then calling the function replace-with. I’m passing the orignal text (MyText), pattern string ([Title]) to search and replace with value (Replaced-text).

For example value of MyText is “This is a sample [Title], created by Salman”.

<xsl:variable name=MyTextReplaced>
   <
xsl:call-template name=string-replace>
      <
xsl:with-param name=text select=xml/MyText />
      <
xsl:with-param name=pattern select=‘[Title]‘ />
      <
xsl:with-param name=replace-with select=‘Replaced-Text’ />
   </
xsl:call-template>
</
xsl:variable>

Now here I’m displaying the replaced string. The output string will be “This is a sample Replaced-Text, created by Salman”. One more thing to notice is that this is a replace-all method and will replace all the occurrence of searched text.
<xsl:value-of select=$MyTextReplaced disable-output-escaping=yes />
 
I hope you enjoy it.

Cheers.

Categories: XSLT Tags: , ,

Use querystring values in xsl

July 17th, 2009 Comments off

It’s just a small tip of the day. Sometime when you work with xsl you need to use querystring values for some processing or display. It’s very simple to use querystring values without posting them from server side code in your xml document.

On top of your xsl document just define a variable like this

<xsl:param name=qs-title/>

here title is a querystring variable and now you can use this xsl variable any where like this

<xsl:value-of select=$qs-title />
 

 

Is not it simple enough?

Categories: XSLT Tags: ,