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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With