Skip to main content

  | मौसम…

411 समाचार
Public archive edition · Attributed source reporting with original dates · AI drafts are excluded

411 REFERENCE · Wikibooks

XQuery/Returning the Longest String

Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.

Motivation You want to find the longest string(s) in a sequence of strings. Sample Program 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 := <tags> <tag>Z</tag> <tag>Ze</tag> <tag>Zee</tag> <tag>Zen</tag> <tag>Zenith</tag> <tag>nith</tag> <tag>ith</tag> <tag>Zenth</tag> </tags> return <results> <max-string>{local:max-length(($tags/tag))}</max-string> </results> [/basics/longeststring.xq Execute] Results <results> <max-string>Zenith</max-string> </results> Discussion 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]