Question

I have the following xml structure :

<reviews>
<review>
    <review_no>R1</review_no>
    <movie_title>After.Life</movie_title>
    <rating>3</rating>
    <reviewer>John Frankenheimer</reviewer>
    <review_date>2012-11-07</review_date>
    <review_desc>Average</review_desc>
</review>
    ...
</reviews>

and the following XQuery :

<query2>
{
for $r in distinct-values(doc("reviews.xml")/reviews/review/reviewer)

return
    <output><reviewer> {data(parent::node()/movie_title)} </reviewer>
    </output>
}
</query2>

The output I get is series of

<output><reviewer/></output>

inside <query2> tags, when instead reviewer tags should contain movie_title data.

Why ?

Was it helpful?

Solution

In case your XQuery processor does not support group by, you will need to perform an (implicit) join. Very similar to your query, but fetch all reviewers and for each, query the reviewers using a predicate.

<query2>
  <output>
    {
      for $reviewer in distinct-values(doc("reviews.xml")/reviews/review/reviewer)
      return <reviewer>
               {
                 /reviews/review[reviewer = $reviewer]/movie_title
               }
             </reviewer>
    }
  </output>
</query2>

OTHER TIPS

distinct-values returns only values, not nodes, so parent::node() does not work.

What is your expected output? You didn't specify your real problem. I guess you want to find all movie_titles grouped by reviewer. If so, group by will be very helpful for you:

<query2>
  <output>
    {
      for $review in doc("reviews.xml")/reviews/review
      let $reviewer := $review/reviewer
      group by $reviewer
      return <reviewer>{$review/movie_title}</reviewer>
    }
  </output>
</query2>

If you do not want the <movie_title/>-tags, you can wrap data() around $review/movie_title.

The problem in your query is that a FLWOR expression does not set the context item: so instead of parent::node(), you need $r/parent-node().

This is a very easy mistake to make if you are used to XSLT, and I make it all the time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top