xsl:with-param

  1. with-param_1-input.xml

  2. <?xml version="1.0"?>
  3. <products>
  4.   <product id="p1" price="3250" stock="4"/>
  5.   <product id="p2" price="1000" stock="5"/>
  6.   <product id="p3" price="1200" stock="19"/>
  7. </products>
  1. with-param_1-stylesheet.xsl

  2. <?xml version="1.0"?>
  3. <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
  4.   <xsl:output indent="yes"/>
  5.   <xsl:template match="/">
  6.     <PRODUCTS>
  7.       <xsl:apply-templates/>
  8.     </PRODUCTS>
  9.   </xsl:template>
  10.   <xsl:template match="product">
  11.     <PRODUCT id="{@id}" price="{@price}" stock="{@stock}">
  12.       <xsl:attribute name="color"><xsl:call-template name="color"><xsl:with-param name="id" select="@id"/></xsl:call-template></xsl:attribute>
  13.     </PRODUCT>
  14.   </xsl:template>
  15.   <xsl:template name="color">
  16.     <xsl:param name="id"/>
  17.     <xsl:choose>
  18.       <xsl:when test="$id = 'p1'">green</xsl:when>
  19.       <xsl:when test="$id = 'p2'">blue</xsl:when>
  20.       <xsl:otherwise>white</xsl:otherwise>
  21.     </xsl:choose>
  22.   </xsl:template>
  23. </xsl:stylesheet>
  1. with-param_1-output.xml

  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <PRODUCTS>
  4.   <PRODUCT id="p1" price="3250" stock="4" color="green"/>
  5.   <PRODUCT id="p2" price="1000" stock="5" color="blue"/>
  6.   <PRODUCT id="p3" price="1200" stock="19" color="white"/>
  7. </PRODUCTS>

Comment

The called template must declare the same parameter in order to pick up the value. Parameters can also be used at global level acting like an external variable getting its value from outside the stylesheet, see: xsl:param.

Parameters can also be sent from template to template with xsl:apply-templates.

Updated 2009-03-19