Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XQuery Nested For Return

I don't quite understand how to use the for nested within a return. For example, given

<book year="1994">
    <title>TCP/IP Illustrated</title>
    <author><last>Stevens</last><first>W.</first></author>
    <publisher>Addison-Wesley</publisher>
    <price>65.95</price>
</book>

<book year="1992">
    <title>Advanced Programming in the Unix environment</title>
    <author><last>Stevens</last><first>W.</first></author>
    <publisher>Addison-Wesley</publisher>
    <price>65.95</price>
</book>

I want to return the following:

<price group = "65.95">
    <book year = "1994">
    <book year = "1992">
</price>

But with the code I wrote, I am getting the error Undefined variable $b. I was wondering if someone could show me where I'm going wrong. Thanks! Here is my code:

    for $p in distinct-values(//price)
return<price group ="{$p}">
(
  for $b in //book[price = $p]
    return <book year = "{$b/@year}"></book>
)
</price>
like image 751
user2266603 Avatar asked Apr 10 '13 14:04

user2266603


1 Answers

The problem is that everything inside the <price group="... element is interpreted as XML. If you want it to be run as XQuery, you have to wrap it in braces {...}:

for $p in distinct-values(//price)
return <price group="{$p}">{
  for $b in //book[price = $p]
  return <book year="{$b/@year}"/>
}</price>

In you code only {$b/@year} is interpreted as XQuery, while the enclosing FLWOR expression is an XML text node. That's why the query processor complains about an undefined variable.

like image 141
Leo Wörteler Avatar answered Nov 13 '22 00:11

Leo Wörteler