[xquery-talk] Problem in validating XQuery

Michael Kay mike at saxonica.com
Mon Oct 1 00:49:08 PDT 2007

> I have the following query:
> xquery version "1.0";
> declare default element namespace "http://www.example.org/driving";
> declare variable $directionsTag :=
> doc("driving.xml")/drivingreport/directions;
> declare variable $startoutTag := $directionsTag/startout;
> declare variable $driveDirections := $directionsTag/drivedirections/*;
> <straight>
> {
>     for $i in $driveDirections
>     return 
>        <start>{$startoutTag/on/text()}</start>
>        <dist>{$startoutTag/@distanceMiles}</dist>
>        if(fn:compare($i/text(), 'turnonto')) then 

The problem is a missing "{" before the if (a very common mistake). This
means that the whole expression from here to the "else ()" is interpreted as
literal text, not as an XQuery expression. Usually this results in the
expression being copied as text to the result document, or in references to
undeclared variables, but in your case you included the closing "}", and
this wouldn't be valid in literal text (it has to be escaped as "}}") so the
parser reported the error at this point.

>             else if(fn:compare($i/text(), 'becomes')) 

compare() returns -1, 0, or +1, and 0 is treated as false, anything else as
true. So this is an odd way of writing if($i/text() ne 'becomes'), which
itself should probably be written if($i ne 'becomes') unless you really want
it to fail when the element contains comments or processing instructions.

Michael Kay

More information about the talk mailing list