xsl:function

  1. function_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. function_1-stylesheet.xsl

  2. <?xml version="1.0"?>
  3. <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0" xmlns:jesper="http://www.xmlplease.com" exclude-result-prefixes="jesper">
  4.   <xsl:function name="jesper:color">
  5.     <xsl:param name="id"/>
  6.     <xsl:choose>
  7.       <xsl:when test="$id = 'p1'">green</xsl:when>
  8.       <xsl:when test="$id = 'p2'">blue</xsl:when>
  9.       <xsl:otherwise>white</xsl:otherwise>
  10.     </xsl:choose>
  11.   </xsl:function>
  12.   <xsl:output indent="yes"/>
  13.   <xsl:template match="/">
  14.     <PRODUCTS>
  15.       <xsl:apply-templates/>
  16.     </PRODUCTS>
  17.   </xsl:template>
  18.   <xsl:template match="product">
  19.     <PRODUCT id="{@id}" price="{@price}" stock="{@stock}" color="{jesper:color(@id)}"/>
  20.   </xsl:template>
  21. </xsl:stylesheet>
  1. function_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

xsl:function is new in XSLT 2.0. Now we can call a user-defined function from an attribute constructed the literal way. Note that a user-defined function must be in a namespace of its own.

Updated 2009-03-19