views:

57

answers:

2

Hi,

Im new to XSLT for the 'PrimarySubject' below I need to replace'&' characters to %26 and ' ' characters to %20 that it contains.

<xsl:template name="BuildLink"> 
    <xsl:param name="PrimarySubject" /> 
    <xsl:text>?PrimarySubject=</xsl:text> 
    <xsl:value-of select="$PrimarySubject" /> 
</xsl:template> 

Is there string replace function I can use in xslt version 1 ? Thanks,

A: 

There are several substring functions in XSLT:

  • string substring-before(string, string)
  • string substring-after(string, string)
  • string substring(string, number, number?)
Oded
+3  A: 

This can be done most easily using the FXSL Library, more exactly its str-map template.

Here is a simple example.

This transformation:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:testmap="testmap"
exclude-result-prefixes="xsl testmap"
>
   <xsl:import href="str-map.xsl"/>

   <!-- to be applied on any xml source -->

   <testmap:testmap/>

   <xsl:output omit-xml-declaration="yes" indent="yes"/>

   <xsl:template match="/">
     <xsl:variable name="vTestMap" select="document('')/*/testmap:*[1]"/>
     <xsl:call-template name="str-map">
       <xsl:with-param name="pFun" select="$vTestMap"/>
       <xsl:with-param name="pStr" select="'abc&amp;d f'"/>
     </xsl:call-template>
   </xsl:template>

    <xsl:template match="testmap:*">
      <xsl:param name="arg1"/>

      <xsl:choose>
       <xsl:when test="$arg1 = '&amp;'">%26</xsl:when>
       <xsl:when test="$arg1 = ' '">%20</xsl:when>
       <xsl:otherwise><xsl:value-of select="$arg1"/></xsl:otherwise>
      </xsl:choose>
    </xsl:template>

</xsl:stylesheet>

when applied on any XML document (not used), produces the wanted result:

abc%26d%20f

Dimitre Novatchev
Better to use a library someone else has written, save a bit of time in the "I didn't think of that situation".
Nat
@Nat, Of course, users of FXSL rarely, if at all, need to implement recursion themselves.
Dimitre Novatchev
Nice post +1 [15 chars]
infant programmer
@infant-programmer Nice to see you, what is the meaning of "[15 chars]"in your comment?
Dimitre Novatchev
Thanks a lot. One more question is how would i pass the value of vTestMap as a parameter to another template? I tried below but it doesnt work...<xsl:call-template name="BuildLink"><xsl:with-param name="PrimarySubject" select="$vTestMap" /></xsl:call-template>
nav
@nav the code in my answer passes $vTestMap as parameter already... There must be a problem in your code, but without seeing the code it's impossible to guess (for me, at least) what is wronf.
Dimitre Novatchev
Sorry your code did work. It was just nuances of working with sharepoint that I couldnt use this solution. Due to errors with import statement, otherwise this would have worked for me :)
nav