2013-04-10 138 views
3

我不太明白如何使用嵌套在返回中。例如,給定XQuery嵌套返回

<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> 

我想返回以下內容:

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

但隨着我寫的代碼,我收到錯誤未定義變量$ B。我想知道如果有人能告訴我我要去哪裏錯了。謝謝! 這裏是我的代碼:

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

回答

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> 

在你的代碼只{$b/@year}被解釋爲XQuery的,而封閉FLWOR表達式是一個XML文本節點。這就是查詢處理器抱怨未定義變量的原因。

+0

謝謝。我認爲這是這樣簡單的事情,但只是不知道究竟是什麼。 – user2266603 2013-04-10 17:05:52