我正在尝试创建一个函数,它接受一个婴儿车,然后根据输入以多种方式查询输入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>
答案 0 :(得分:5)
这是根据它所声明的W3C specification ......
在样式表函数的主体内,最初的重点是 不确定的;这意味着任何引用上下文项的尝试, 上下文位置或上下文大小是不可恢复的动态错误。
解决方案是将节点(例如根节点)作为参数传递
<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>
或者,您可以考虑使用命名模板而不是函数,可能:
<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>