Update the text of an element with XSLT based on param

There are a number of problems with the provided code which lead to compile-time errors:

<xsl:template match="/foo/bar/"> 
    <xsl:param name="baz" value="something different"/> 
        <xsl:value-of select="$baz"/> 
</xsl:template>
  1. The match pattern specified on this template is syntactically illegal — an XPath expression cannot end with the / character.

  2. xsl:param cannot have an unknown attribute such as value

Solution:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:param name="pReplacement" select="'Something Different'"/>

 <xsl:template match="node()|@*">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>

 <xsl:template match="foo/bar/text()">
  <xsl:value-of select="$pReplacement"/>
 </xsl:template>
</xsl:stylesheet>

When this transformation is applied on the provided XML document:

<foo>
  <bar>
    baz
  </bar>
</foo>

the wanted, correct result is produced:

<foo>
   <bar>Something Different</bar>
</foo>

Leave a Comment