XQuery with if condition in for loop

user991255 picture user991255 · Mar 10, 2015 · Viewed 8k times · Source

I have written xquery to return results in normal way.

let $results := //data:data
return 
  <result>
  {
    for $i in $results
    return
      <documentInformation>
        <id>{data($i/DATA:ID)}</id>
        <status>{data($i/@status)}</status>
        <title>{data($i/data:title)}</title>
        <displayName>{data($i/DATA:DISPLAYNAME)}</displayName>
      </documentInformation>
  }
  </result>

Now, I have to filter out the results in for loop with some condition like

(pseudo logic)
if id = 'abc' and status ="closed"  
then skip the row
else add row.

I have tried several ways. but could not run the query..

Answer

Dave Cassel picture Dave Cassel · Mar 10, 2015

Try this:

<result>
{
  for $i in //data:data
  where fn:not($i/DATA:ID = 'abc' and $i/@status = "closed")
  return
    <documentInformation>
      <id>{data($i/DATA:ID)}</id>
      <status>{data($i/@status)}</status>
      <title>{data($i/data:title)}</title>
      <displayName>{data($i/DATA:DISPLAYNAME)}</displayName>
    </documentInformation>
}
</result>

Note that the XPath //data:data may have a lot of work to do, but that's a separate matter.