2013-05-03 35 views
2

我有一個任務來創建一個xml文件並使用XQuery查詢它。該文件看起來大致是這樣的:XQuery:簡單查詢示例

<library> 
    <book> 
     <title>Title1</title> 
     <author>Author1</author> 
     <author>Author2</author> 
     <subject>Subject1</subject> 
    </book> 
    <book> 
     <title>Title2</title> 
     <author>Author3</author> 
     <subject>Subject1</subject> 
    </book> 
</library> 

對於每一個作者,我應該還書的標題,所以很明顯標題1,應兩次返回。

我一直是這樣的:

let $a:=doc("/home/user/library.xml")/library/book 
for $x in $a/title, $y in $a/author 
return $x 

我得到的結果是: 標題1 標題2 標題1 標題2 標題1 標題2

我看到的問題是對於每位作者,我都會返回每本書名,但我不確定如何讓它只返回與特定作者對應的書名。有什麼建議麼?

謝謝!

回答

2

使用

for $author in distinct-values(/*/*/author) 
    return 
     /*/book[$author = author]/title/string() 

當該XPath表達式(即也XQuery中,因爲XPath是XQuery的的一個子集)的針對提供的XML文檔評價:

<library> 
    <book> 
     <title>Title1</title> 
     <author>Author1</author> 
     <author>Author2</author> 
     <subject>Subject1</subject> 
    </book> 
    <book> 
     <title>Title2</title> 
     <author>Author3</author> 
     <subject>Subject1</subject> 
    </book> 
</library> 

想要的,正確的結果是:

Title1 Title1 Title2 
+0

謝謝,這真的很有幫助。我忘記了如何使用XPath正確導航。 – coffeeNjava 2013-05-03 14:00:33

+0

@coffeeNjava,不客氣。我建議從一本關於XPath的好書開始。 – 2013-05-03 14:24:31