Vallabh Lakade
Vallabh Lakade

Reputation: 832

User defined functions in XSL

I am trying to create a user defined function "fetchXMLAttribute" in XSL.For now i am just printing "abcd" inside it.Following is my XSL file

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xsl:function name="fetchXMLAttribute">     
    abcd
</xsl:function>

 <xsl:output method="xml"   doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"    indent="yes"    encoding="utf-8" />
<xsl:template match="/*">
    <html>
        <body>             
            <div>       
                <xsl:attribute name="xmlAttribute">  
                    <xsl:value-of select="fetchXMLAttribute()"/> 
                </xsl:attribute>
            </div>
        </body>
    </html>
</xsl:template>

I have tried some examples but none of them worked.I found use of some namespace for user defined functions.Is that really necessary even if i have my function written inside the same XSL file?I am getting this error :

ERROR:  'Could not compile stylesheet'FATAL ERROR:  'Error checking type of the expression 'funcall(fetchXMLAttribute, [])'.'
       :Error checking type of the expression 'funcall(fetchXMLAttribute, [])'.Exception in conversion javax.xml.transform.TransformerConfigurationException: Error checking type of the expression 'funcall(fetchXMLAttribute, [])'.

Upvotes: 1

Views: 1960

Answers (1)

Tomalak
Tomalak

Reputation: 338336

Functions must have a namespace.

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:my="http://tempuri.org/mynamespace"
    xmlns="http://www.w3.org/1999/xhtml"
    exclude-result-prefixes="xs my"
>
    <xsl:output method="xml" indent="yes" encoding="utf-8"
        doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
        doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" />

    <xsl:function name="my:fetchXMLAttribute">
        <xsl:text>abcd</xsl:text>
    </xsl:function>

    <xsl:template match="/*">
        <html>
            <body>             
                <div xmlAttribute="{my:fetchXMLAttribute()}"> 
                </div>
            </body>
        </html>
    </xsl:template>
</xsl:stylesheet>

Also note

  • the default namespace is set to XHTML
  • namespaces xs and my are excluded from the output
  • <xsl:text> to avoid unwanted whitespace
  • the attribute value template (attr="{xpath-expression}")

Upvotes: 2

Related Questions