Search code examples
xmldebuggingxqueryflwor

Xquery using FLWOR Expression Query


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 ?


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>