pythonxpathxqueryberkeley-db-xml

XQuery: comparing datetimes with milliseconds


I have a validation module in Python that executes an XQuery on an XML document to check if any <Start> times come after <End> times, and return the count of them. The query is as follows:

    for $d at $count in ./ty:Detections/Detection
        where $d/Start > $d/End
        return $count

Now this works fine and good for all cases except when milliseconds are appended to an End time but not a Start time, e.g.:

        <Start>2009-02-23T02:53:14Z</Start>
        <End>2009-02-23T02:53:14.226Z</End>

This always returns True, even though clearly 14 is less than 14.22. If I add a single decimal place to the <Start> time here, it works -- but is there any better solution?


Solution

  • Presumably there is no schema binding in effect for the Start and End elements. In that case the query is doing an xs:untypedAtomic comparison, which effectively compares the string values, where "Z" compares greater than ".".

    What you want is an xs:dateTime comparison, so you should compare the element values after casting them to that type. The query thus should look like:

        for $d at $count in ./ty:Detections/Detection
        where xs:dateTime($d/Start) > xs:dateTime($d/End)
        return $count