Shane McGarry
Shane McGarry

Reputation: 547

XQuery returns items not in set

I am writing some XQuery on the following document:

<pages>
   <page>
      <content yearID="1998">
         <month monthID="1">
            ...
         </month>
         <month monthID="2">
            ...
         </month>
         ...
      </content>
   <page>
</pages>

I want to query the document for a given year and month and have it return the entire node with just that month (no other months included). My XQuery is as follows:

for $x in doc("alcala/ledger.xml")//pages/page
where $x/content[@yearID="1998"] and $x/content/month[@monthID="2"] 
return $x

My result is giving me both months 1 and 2. If I search for monthID="3", I get months 2 and 3. I've tried just a search on the month (without the year filter) and I get the same results. Why is it giving me part of the previous month along with the month I want? How do I remove the month I do not want?

Upvotes: 3

Views: 119

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167716

So far you are simply selecting page elements from the input that meet your where condition. If you want to manipulate the input (i.e. remove a month you are not interested in) you need to construct the new contents, for instance a simple approach is to use

for $x in /pages/page
where $x/content[@yearID="1998"] and $x/content/month[@monthID="2"]
return 
    <page>{
        $x/content[@yearID = 1998]
        !<content>{
            @*, month[@monthID = 2]
                !<month>{@*, node()}</month>
        }</content>
    }</page>

although that way you have to write some of the conditions twice.

Upvotes: 3

Related Questions