Reputation: 259
I have an assignment to create an xml file and query it using XQuery. The file looks roughly like this:
<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>
For each author, I'm supposed to return the title of the book, so obviously Title 1 should be returned twice.
I've been trying something like this:
let $a:=doc("/home/user/library.xml")/library/book
for $x in $a/title, $y in $a/author
return $x
The results I'm getting are: Title1 Title2 Title1 Title2 Title1 Title2
I see that the problem is that for every author, I'm returning every book title, but I'm not sure how to get it to return only the book titles that correspond to a particular author. Any suggestions?
Thanks!
Upvotes: 2
Views: 213
Reputation: 243529
Use:
for $author in distinct-values(/*/*/author)
return
/*/book[$author = author]/title/string()
When this XPath expression (that is also XQuery, because XPath is a subset of XQuery) is evaluated against the provided XML document:
<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>
the wanted, correct result is produced:
Title1 Title1 Title2
Upvotes: 2