Home > XQuery Resources > XQuery Tutorial> Logical Expressions
Logical expressions return boolean values, and aritrarily complex logical expressions can be created using "and" and "or" operators. This section shows some expressions that use logical expressions such as If-then-else:

 
{-- IfExpr using built in function contains() --}

<result>
{
for $a in document("data/R-items.xml")//item_tuple
return
  <my_item>
  {
    $a/description,
    <cycle>
    {
      if (contains($a/description, "cycle")) then "YES"
        else "NO"
    }
    </cycle>
  }
  </my_item>
}
</result>





{-- nested if-then-else --}

<result>
{
for $a in document("data/R-items.xml")//item_tuple
return
  <my_item>
  {
    $a/description,
    $a/reserve_price,
    <cycle>
    {
      if (contains($a/description, "cycle"))
      then
        if (number($a/reserve_price) < 200)
        then
          "Cycle less than 200"
        else
          "Cycle greater or equal 200"
      else
        if (number($a/reserve_price) < 200)
        then
          "Not a cycle and cheap"
        else
          "Not a cycle, but expensive"
    }
    </cycle>
  }
  </my_item>
}
</result>





{-- deeply nested if-then --}

<result>
{
for $a in document("data/parts-data.xml")//part
return
  if ($a/@name = "car")
  then <my_car> { $a/@* } </my_car>
  else if ($a/@name = "engine")
  then <my_engine> { $a/@* } </my_engine>
  else if ($a/@name = "door")
  then <my_door> { $a/@* } </my_door>
  else if ($a/@name = "piston")
  then <my_piston> { $a/@* } </my_piston>
  else if ($a/@name = "window")
  then <my_window> { $a/@* } </my_window>
  else if ($a/@name = "lock")
  then <my_lock> { $a/@* } </my_lock>
  else if ($a/@name = "skateboard")
  then <my_skateboard> { $a/@* } </my_skateboard>
  else if ($a/@name = "board")
  then <my_board> { $a/@* } </my_board>
  else if ($a/@name = "wheel")
  then <my_wheel> { $a/@* } </my_wheel>
  else if ($a/@name = "canoe")
  then <my_canoe> { $a/@* } </my_canoe>
  else
    <my_unknown/>
}
</result>





{-- boolean expr: udf returning boolean --}

define function isEven(integer $n) returns boolean
{
  if (($n mod 2) = 0) then true() else false()
}

<result>
{
  for $n in document("data/parts-data.xml")//part/@partid
  return
    <test>
    {
      concat(string($n), if (isEven($n)) then " is even"
        else " is odd")
    }
    </test>
}
</result>





{-- boolean expr: udf returning boolean from FLWR expr --}

define function hasInstrument($action as node) as xs:boolean {
  let $instrument := $action/instrument
  return
    if ($instrument) then true() else false()
}

<result>
{
  for $a in document("data/seq-data.xml")//action
  return
    <my_action>
    {
      $a,
      <has_instrument>
      {
        if (hasInstrument($a)) then "YES" else "NO"
      }
      </has_instrument>
    }
    </my_action>
}
</result>

 


Company | Products | Solutions | News & Events | Developers | Contact Us | Site Map