Reputation: 569
I am writing Xquery function for BaseX which gets one of arguments as name of the element node. This name is then used in Xpath, but in general I cannot convert string to element.
This is how the method looks like
declare function prefix:getElementWithValue($root as document-node()?, $elem as xs:string?, $minVal as xs:float?, $maxVal as xs:float?)
as element()*
{
let $e := element {$elem} {""}
for $x in $root//SUBELEM
return if ($x//$e/@ATTRIB>=$minVal and $x//$e/@ATTRIB<=$maxVal) then ($x)
};
and the call
return prefix:getElementWithValue($db, "SomeElem", 10.0, 10.0)
and I am getting empty response from that. If I replace the $x//$e
with $x//SomeElem
it returns proper response. From the QueryPlan I see that the $e
is treated as literal value. XPATH is not $x//SomeElem/@ATTRIB
but $x//$e/@ATTRIB
So my question is how to covert string to type that can be used in XPATH?
Upvotes: 0
Views: 586
Reputation: 163262
XQuery does not have a standard function to evaluate a dynamically-constructed XPath expression.
Many XQuery processors offer some kind of extension function that does this, however. For example, BaseX offers query:eval():
https://docs.basex.org/wiki/XQuery_Module#xquery:eval
Note that variables in XQuery represent values, not fragments of expression text. Your expression $x//$e/@ATTRIB
is equivalent to $x//"SomeElem"/@ATTRIB
, which is quite different from $x//SomeElem/@ATTRIB
.
If you know that $elem
will always be an element name, then you can write $x//*[name()=$e]/@ATTRIB
. But take care over namespaces.
Upvotes: 3