how to use if else in xquery assignment

sony picture sony · Sep 10, 2010 · Viewed 68.8k times · Source

I am trying to use a if condition to assign a value to a variable in an xquery. I am not sure how to do this.

This is what I tried:

declare namespace libx='http://libx.org/xml/libx2';
declare namespace atom='http://www.w3.org/2005/Atom';
declare variable $entry_type as xs:string external;
let $libx_node :=
    if ($entry_type = 'package' or 'libapp') then
      {element {fn:concat("libx:", $entry_type)} {()} }
    else if ($entry_type = 'module') then
      '<libx:module>
        <libx:body>{$module_body}</libx:body>
      </libx:module>'

This code throws an [XPST0003] Incomplete 'if' expression error. Can someone help me fix this?

Also, can someone suggest some good tutorials to learn xqueries.

Thanks, Sony

Answer

Shcheklein picture Shcheklein · Sep 10, 2010

That's because in XQuery's conditional expression specification else-expression is always required:

[45]  IfExpr  ::=  "if" "(" Expr ")" "then" ExprSingle "else" ExprSingle

So you have to write second else clause (for example, it may return empty sequence):

declare namespace libx='http://libx.org/xml/libx2';
declare namespace atom='http://www.w3.org/2005/Atom';
declare variable $entry_type as xs:string external;

let $libx_node :=
        if ($entry_type = ('package','libapp')) then
          element {fn:concat("libx:", $entry_type)} {()}
        else if ($entry_type = 'module') then
          <libx:module>
            <libx:body>{$module_body}</libx:body>
          </libx:module>
        else ()
... (your code here) ...

Some obvious bugs are also fixed:

  • don't need {} around computed element constructor;
  • most likely, you want if($entry_type = ('package', 'libapp'))

Concerning XQuery tutorials. The W3CSchools's XQuery Tutorial is a pretty good starting point.