I am trying to use a custom function in XSLT that repeatedly calls the value of a specific string. This line is based on the result of an XPath expression that does not change within the range of a single function call. I thought it would be nice to assign it to a variable, and not look for it again and again.
Unfortunately, at least in a Saxon implementation, you cannot use an XPath expression that requires a node inside a function, not even one based on an absolute path, without using a drop line, so that the function can know that you are discussing the root document, not some then another.
So, for example, the following code raises an error:
<xsl:function name="udf:LeafMatch"> <xsl:param name="sID"></xsl:param> <xsl:variable name="myLeaf" select="/potato/stem[@sessionID=$sID][scc]/scc/@leafnumber"/>
Usually the solution is to first call any global variable to give context. For example, the following actions inside udf ($ root is a variable identified with the root of the node):
<xsl:for-each select="$root"> <xsl:value-of select="/potato/stem[@sessionID=$sID][scc]/scc/@leafnumber"/> </xsl:for-each>
But this does not work when trying to use Xpath to correct the value of a variable, because I am not allowed to put an expression inside each of them.
I also tried using
<xsl:choose><xsl:when select"$root"><xsl:value-of select="/potato/stem[@sessionID=$sID][scc]/scc/@leafnumber"/></xsl:when></xsl:choose>
to give it context, continuing what I saw here: http://www.stylusstudio.com/xsllist/200504/post00240.html
That didn't work either.
FWIW, passing a variable to a function is problematic because the Xpath expression used to define "myleaf" depends on the context of the node, and I don't know how to get Xpath to call one path based on the values in the current node context.
For example, in the code that calls this function, I have something like:
<xsl:for-each select="/potato/stem[eye]"> <leaf = "{udf:LeafMatch(@sessionID)}"/> </xsl:for-each>
I work in the context of / potato / stem [eye] node and using udf to search for / potato / stem [scc] node, which has the same @sessionID value. I don’t know how to refer to the @sessionID value from the current node context in the XPath predicate, which is looking for other nodes in a completely different part of the XML tree, so I used udf to do this. It worked fine until I decided to use a variable for the string, and not every time the processor looked at it.
I tried to avoid going one level deeper (my function itself called the named template or put the named template inside my original for each of them and had this name template calling the function).
So my questions are:
a. For a custom function, how do I set a variable that depends on an XPath expression?
Q. Is there a cool way in Xpath to use the values obtained from the current node content in the predicates of the Xpath expression that you are trying to test?