Not yet rated

Problem

You need functions in your templates that XSLT itself does not provide.

Solution

Include a Java namespace.

Detailed explanation

Sometimes you could use some simple functions that XSLT (especially XSLT 1) does not provide. A Xalan based processor like ColdFusion's gives access to the entire Java world behind the scenes.

For instance, when you need encoded urls in your output (%20 etc.) then simply include java.net.URLEncoder as a namespace:

xmlns:urlfunc="java.net.URLEncoder"

and url encoding is as simple as this:

<a href="{urlfunc:encode(./url)}">go</a>

What about random numbers? Add a namespace

xmlns:rnd="java.util.Random" 

and off you go:

<xsl:value-of select="rnd:nextInt(1000)" />

For the sake of clarity an XSLT template:

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:urlfunc="java.net.URLEncoder"
    xmlns:rnd="java.util.Random"
    exclude-result-prefixes="urlfunc rnd"
>   

    ... 

    <a href="{urlfunc:encode(./url)}">go</a> 

    <xsl:value-of select="rnd:nextInt(1000)" />

    ...

</xsl:stylesheet>

There's a lot more to say about this subject and there are other possibilities as well, including EXSLT, but these examples provide a simple way to deal with some very common problems.


+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes