XQuery嵌套返回

use*_*603 3 xml xquery xml-parsing

我不太明白如何在返回中使用for嵌套.例如,给定

<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>
Run Code Online (Sandbox Code Playgroud)

我想返回以下内容:

<price group = "65.95">
    <book year = "1994">
    <book year = "1992">
</price>
Run Code Online (Sandbox Code Playgroud)

但是根据我编写的代码,我收到错误Undefined variable $ b.我想知道是否有人能告诉我哪里出错了.谢谢!这是我的代码:

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

Leo*_*ler 5

问题是<price group="...元素中的所有内容都被解释为XML.如果你想让它作为XQuery运行,你必须将它包装在大括号中{...}:

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

在您的代码中,只{$b/@year}将代码解释为XQuery,而封闭的FLWOR表达式是XML文本节点.这就是查询处理器抱怨未定义变量的原因.