3

I am trying to create a function that takes one pram and then queries the input XML in several ways based on the input. My problem is that when I try to query the input xml and store a value in a variable while in the function I get the error:

'/' cannot select the root node of the tree containing the context item: the context item is absent

How can I query the XML from within the 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>   
1
  • 1
    Note: your function is not doing anything, currently. It only defines a variable, but doesn't use that variable anywhere. Commented Aug 17, 2014 at 14:51

1 Answer 1

5

This is as per the W3C specification where it states...

Within the body of a stylesheet function, the focus is initially undefined; this means that any attempt to reference the context item, context position, or context size is a non-recoverable dynamic error.

The solution is to pass in a node (such as the 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 could consider using 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>
Sign up to request clarification or add additional context in comments.

1 Comment

And, as a third alternative, global variables do have access to the global context item. You can bind a global variable to the root and reference that <xsl:variable name="root" select="root()" />. But passing a reference as in Tim's first example is the preferred and natural way of doing it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.