0
votes

I am new to XML / Xquery and am having trouble figuring this out. In the XML document provided below, I am trying to find all the authors that wrote a book with the same name, and the rating associated with that book. The problem that I am having is that my query is returning all the ratings for an author that might have multiple books as well as the one being looked for.

XML Doc:

<lib>
<author name="Sally J">
    <book>
        <name>ABC</name>
        <rating>6</rating>
    </book>
    <book>
        <name>Monsters</name>
        <rating>2</rating>
   </book>
    <book>
        <name>Spring Poems</name>
        <rating>5</rating>
   </book>
</author>
<author name="Samantha G">
    <book>
        <name>ABC</name>
        <rating>2</rating>
    </book>
    <book>
        <name>Cooking101</name>
        <rating>7</rating>
   </book>
    <book>
        <name>Aliens?</name>
        <rating>10</rating>
   </book>
</author>
</lib>

My Query:

 for $x in doc("lib.xml")/lib/author
 where $x/book/name="ABC"
 return ($x/@name, $x/book/rating)

What it outputs is:

Sally J

6

2

5

Samantha G

2

7

10

When I only want the rating of the book "ABC" for each author that has one. I am sure the solution is simple, but I just lack a concrete understanding of how things work in Xquery.

1

1 Answers

0
votes

What your query says is: for each author, if there is some book by that author whose name equals 'ABC', return the name of the author and the rating of all the books of that author. Which is what you see. The thing to keep in mind is that XPath returns sequences of results, so $x/book/rating is the set of all rating children of all book children of $x. What you want is the rating of the book whose name equals 'ABC', so you're going to have to put the condition there too:

for $x in doc("lib.xml")/lib/author[book/name="ABC"] 
return ($x/@name, $x/book[name="ABC"]/rating)