StellaMaris
StellaMaris

Reputation: 867

Calling a function in XSLT

I try to run one of the functions which are linked bellow in my own stylesheet. But I dont know how.

Here is an xsltransform.net demo.

And here are the functions I want to run:

func 1

func 2

Upvotes: 3

Views: 10685

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167716

Assuming an XSLT 2.0 processor like Saxon 9 you can use xsl:function as follows:

<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="2.0"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:func="http://example.com/mf">

    <xsl:output method="html" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="/">
        <div>
            <ul>
                <xsl:apply-templates/>
            </ul>
        </div>
    </xsl:template>

    <xsl:template match="xs:element">
        <li xPath="{func:generateXPath(.)}">
            <xsl:value-of select="@name"/>
            <xsl:if test="xs:*">
                <ul>
                    <xsl:apply-templates/>
                </ul>
            </xsl:if>
        </li>
    </xsl:template>

    <xsl:function name="func:generateXPath" as="xs:string" >
        <xsl:param name="pNode" as="node()"/>
        <xsl:value-of select="$pNode/ancestor-or-self::*/name()" separator="/"/>

    </xsl:function>



</xsl:stylesheet>

With some XSLT 1.0 processors like Saxon 6 and I think Xalan or XsltProc you can use

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0"
  xmlns:func="http://exslt.org/functions"
  xmlns:mf="http://example.com/mf"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  exclude-result-prefixes="func mf xs">

    <xsl:output method="html" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="/">
        <div>
            <ul>
                <xsl:apply-templates/>
            </ul>
        </div>
    </xsl:template>

    <xsl:template match="xs:element">
        <li xPath="{mf:getXpath()}">
            <xsl:value-of select="@name"/>
            <xsl:if test="xs:*">
                <ul>
                    <xsl:apply-templates/>
                </ul>
            </xsl:if>
        </li>
    </xsl:template> 

<func:function name="mf:getXpath">
   <xsl:variable name="xpath">
      <xsl:for-each select="ancestor-or-self::*">
         <xsl:value-of select="name()"/>
         <xsl:if test="not(position()=last())">
            <xsl:value-of select="'/'"/>
         </xsl:if>
      </xsl:for-each>
   </xsl:variable>
   <func:result select="$xpath" />
</func:function>

</xsl:transform>

Upvotes: 5

Related Questions