function_1-input.xml
<?xml version="1.0"?>
<products>
<product
id="p1" price="3250" stock="4"/>
<product
id="p2" price="1000" stock="5"/>
<product
id="p3" price="1200" stock="19"/>
</products>
function_1-stylesheet.xsl
<?xml version="1.0"?>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0" xmlns:jesper="http://www.xmlplease.com" exclude-result-prefixes="jesper">
<xsl:function
name="jesper:color">
<xsl:param
name="id"/>
<xsl:choose>
<xsl:when
test="$id = 'p1'">green</xsl:when>
<xsl:when
test="$id = 'p2'">blue</xsl:when>
<xsl:otherwise>white</xsl:otherwise>
</xsl:choose>
</xsl:function>
<xsl:output
indent="yes"/>
<xsl:template
match="/">
<PRODUCTS>
<xsl:apply-templates/>
</PRODUCTS>
</xsl:template>
<xsl:template
match="product">
<PRODUCT
id="{@id}" price="{@price}" stock="{@stock}" color="{jesper:color(@id)}"/>
</xsl:template>
</xsl:stylesheet>
function_1-output.xml
<?xml version="1.0" encoding="UTF-8"?>
<PRODUCTS>
<PRODUCT
id="p1" price="3250" stock="4" color="green"/>
<PRODUCT
id="p2" price="1000" stock="5" color="blue"/>
<PRODUCT
id="p3" price="1200" stock="19" color="white"/>
</PRODUCTS>
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