hermit05
hermit05

Reputation: 117

XSLT extensions: I am trying to use a custom java function in XSLT but am not able to pin point the mistake

I am trying to use a factorial function from a java class. The other two functions that I have used are working fine but I don't know what I am doing wrong with the factorial function.

Below is the XSLT:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"     xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:date="java.util.Date" exclude-result-prefixes="#all">
<xsl:output method="html" indent="yes"/>

<xsl:template match="/">
    <xsl:if test="function-available('date:toString') and function-available('date:new')">
        <p><xsl:value-of select="date:toString(date:new())"/></p>
    </xsl:if>
    <xsl:if xmlns:string="java.lang.String" test="function-available('string:toUpperCase')" exclude-result-prefixes="string">
        <p><xsl:value-of select="string:toUpperCase('pune')" /></p>
    </xsl:if>
    <xsl:if xmlns:fact="java" test="function-available('fact:factorial.calculateFactorial')" exclude-result-prefixes="fact">
        <p><xsl:value-of select="fact:factorial.calculateFactorial(5)" /></p>
    </xsl:if>
</xsl:template>

Below is the java class:

public class factorial{
public int calculateFactorial(int number){
    int fact=1;
    while(number>=1){
        fact = fact * number;
        number--;
    }
    return fact;
}
}

The class and the xslt are in the same folder.

The error is:

Error at xsl:value-of on line 13 column 59 of extension-functions.xslt:
  XPST0017: XPath syntax error at char 26 on line 13 in {fact:calculateFactorial(5)}:
Cannot find a matching 1-argument function named {urn:java:factorial}calculateFactorial()
Failed to compile stylesheet. 1 error detected.

Saxon version is: Saxon 9.1.0.8J from Saxonica

Upvotes: 0

Views: 1153

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167516

With Saxon 9.6 PE the following works for me:

<xsl:if xmlns:fact="java:Factorial" test="function-available('fact:new') and function-available('fact:calculateFactorial')" exclude-result-prefixes="fact">
    <p><xsl:value-of select="fact:calculateFactorial(fact:new(), 5)" /></p>
</xsl:if>

Java class is

public class Factorial{
public int calculateFactorial(int number){
    int fact=1;
    while(number>=1){
        fact = fact * number;
        number--;
    }
    return fact;
}
}

command line to call Saxon is

java.exe -cp 'C:\Program Files (x86)\Saxonica\SaxonPE9.6J\saxon9pe.jar;.' net.sf.saxon.Transform .\test2015010101.xml .\test2015010601.xsl

where . contains Factorial.class.

Upvotes: 2

Related Questions