XSLT cannot query input XML from inside a function
I am trying to create a function that takes one stroller and then requests the input XML in multiple ways based on the input. My problem is when I try to query the input xml file and store the value in a variable and in the function I get the error:
'/' cannot select the root node of the tree containing the context element: no context element
How can I request XML from a function? Below is the 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>
source to share
This is in line with the W3C spec where it says ...
Within the body of a stylesheet function, focus is initially undefined; this means that any attempt to reference a context item, context position, or context size is a nonrecoverable dynamic error.
The solution is to pass a node (like root node) as a parameter
<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>
Alternatively, you can use a named template instead of a function, perhaps:
<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>
source to share