XQuery/Returning the Longest String

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Motivation[edit | edit source]

You want to find the longest string(s) in a sequence of strings.

Sample Program[edit | edit source]

xquery version "1.0";

declare function local:max-length($string-seq as xs:string*) as xs:string+ {
  let $max := max (for $s in  $string-seq  return string-length($s))
  return $string-seq[string-length(.) = $max]

let $tags :=



Results[edit | edit source]


Discussion[edit | edit source]

This XQuery creates a local function that takes zero or more strings:

$string-seq as xs:string*

and returns one or more strings:

as xs:string+

It uses the max() XPath function that looks at a sequence of values and returns the highest.

Note that if there are several strings in the input set that each have the same max length, it will return all strings of max length.

If you only want the first returned, add "[1]" to the return expression:

return $string-seq[string-length(.) = $max][1]