Calling a function in XSLT

假如想象 提交于 2021-01-28 04:42:26

问题


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


回答1:


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>


来源:https://stackoverflow.com/questions/34794072/calling-a-function-in-xslt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!