问题
I want to convert the xslt key function to a Xquery function . Can anyone help me in this?
回答1:
If we have an xsl:key
instruction:
<xsl:key name='someName' match="patExpr" use="Expr"/>
and a call to the key()
function:
key('someName', someExpr, $someDocNode)
this is equivalent to:
($someDocNode//patExpr)[Expr = someExpr]
So, for any specific key, you need to declare a function (name it my:keySomeName()
) that returns a sequence of nodes and whose body is the above expression.
Example:
If we have this xsl:key
instruction:
<xsl:key name='kNameByVal' match='Name' use='.'/>
and this call to the key()
function:
key('kNameByVal', 'Peter', $doc)
then the corresponding XQuery function will have this body:
$doc//Name[. = 'Peter']
In case the second operand of the key()
function is a more complex expression, a function that calculates that expression must be passed as the second argument to your key-implementing function (so this is only possible in XQuery 3.0 and up) and we end up with something like this:
declare function my:keyNameByVal($funExpr as function($context as node()) as item()*,
$currenDoc as document-node()
) as node()*
{
$currenDoc//Name[. = $funExpr(.) ]
}
A more traditional, non-3.0 way is that the caller calculates the expression and passes the result of this calculation as the first argument to the my:keyNameByVal()
function:
declare function my:keyNameByVal($useExpr as item()*,
$currenDoc as document-node()
) as node()*
{
$currenDoc//Name[. = $useExpr]
}
}
来源:https://stackoverflow.com/questions/13793199/xquery-function-for-xslt-key-function