Search code examples
xquery

Unable to understand this xquery function


I am new to xquery and unable to understand what does it means :

 declare function my:get-unique-lines($object)
 {
   let $lines := distinct-values (
      for $line in $object[contains(@name," ")]/@name
      return (string-join(tokenize($line," ")[position()< last()]," "))
   )
   return $lines
 };

Solution

  • Well firstly, the variable $lines is obviously redundant. We're left with

    distinct-values (
          for $line in $object[contains(@name," ")]/@name
          return (string-join(tokenize($line," ")[position()< last()]," "))
    

    What string-join(tokenize($line," ")[position()< last()] does is to split $line into tokens at space boundaries, take all tokens except the last, and then join them back together with space as a separator.

    We do that for all the selected @name values, and then remove duplicates.

    So if $object contains a list of element like

    <e name="John Smith"/>
    <e name="John Jones"/>
    <e name="John Henry Jones"/>
    <e name="John Henry Miller"/>
    

    the result will be the two strings "John" and "John Henry".