XSLT无法从函数内查询输入XML

Ale*_*lex 3 xslt xslt-2.0

我正在尝试创建一个函数,它接受一个婴儿车,然后根据输入以多种方式查询输入XML.我的问题是,当我尝试查询输入xml并在函数中存储值时,我得到错误:

'/'无法选择包含上下文项的树的根节点:上下文项不存在

如何从函数中查询XML?下面是XSLT

<xsl:stylesheet version="2.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:lang="info:lc/xmlns/codelist-v1" 
    xmlns:foo="http://whatever">

    <xsl:output indent="yes" />

   <xsl:function name="foo:get-prefered">
       <xsl:param name="field-name"/> 
       <xsl:variable name="var1" select="sources/source[@type='A']/name" />
    </xsl:function>

    <xsl:template match="/">
        <xsl:value-of select="foo:get-prefered(10)"></xsl:value-of>
    </xsl:template>
</xsl:stylesheet>   
Run Code Online (Sandbox Code Playgroud)

Tim*_*m C 5

这符合W3C规范,其中声明......

在样式表函数的主体内,焦点最初是未定义的; 这意味着任何引用上下文项,上下文位置或上下文大小的尝试都是不可恢复的动态错误.

解决方案是将节点(例如根节点)作为参数传递

<xsl:function name="foo:get-prefered">
   <xsl:param name="root"/> 
   <xsl:param name="field-name"/> 
   <xsl:variable name="var1" select="$root/sources/source[@type='A']/name"></xsl:variable>
   <xsl:value-of select="$var1" />
</xsl:function>

<xsl:template match="/">
    <xsl:value-of select="foo:get-prefered(/, 10)"></xsl:value-of>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

或者,您可以考虑使用命名模板而不是函数:

<xsl:template name="get-prefered">
   <xsl:param name="field-name"/> 
   <xsl:variable name="var1" select="sources/source[@type='A']/name"></xsl:variable>
   <xsl:value-of select="$var1" />
 </xsl:template>

 <xsl:template match="/">
    <xsl:call-template name="get-prefered">
        <xsl:with-param name="field-name">10</xsl:with-param>
    </xsl:call-template>
 </xsl:template>
Run Code Online (Sandbox Code Playgroud)

  • 而且,作为第三种选择,全局变量可以访问全局上下文项.您可以将全局变量绑定到根并引用`<xsl:variable name ="root"select ="root()"/>`.但是,在蒂姆的第一个例子中传递参考是这种做法的首选和自然方式. (2认同)