Monday, February 21, 2011

How does one iterate over a sequence in xquery by twos?

I want to iterate over a sequence in xquery and grab 2 elements at a time. What is the easiest way to do this?

From stackoverflow
  • I guess three options could be:

    for $item at $index in $items
      return
      if ($item mod 2 = 0) then
        ($items[$index - 1], $items[$index])
      else
        ()
    

    and another option might be to use mod and the index of the item:

    for $index in 1 to $items div 2
      return
      ($items[($index - 1)*2+1] , $items[($index)*2])
    

    or

    for $index in (1 to fn:count($items))[. mod 2 = 0]
      return
      ($items[$index - 1] , $items[$index])
    
  • for $item at $index in $items return ( if ($index mod 2 eq 0) then ( $items[xs:integer(xs:integer($index) - 1)], $items[xs:integer($index)] ) else () )

  • let $s := ("a","b","c","d","e","f")
    
    for $i in 1 to xs:integer(count($s) div 2)
    return
    <pair>
       {($s[$i*2 - 1],$s[$i*2])} 
    </pair>
    

    returns

    <pair>a b</pair>
    <pair>c d</pair>
    <pair>e f</pair>
    

0 comments:

Post a Comment