Thursday, May 9, 2013

xquery : increment index in for each loop

Unlike java we cannot increment a variable's value in xquery while using for loop.

Say for e.g if we declare the following count variable in xquery and try to use it in the mapping, it will never work as we expect

 let $count := 0
 for $record at $position in $collection/books
                    let $count :=  $count + 1

                    return
                     <ns1:books>
                        <ns1:name>{ $record/name }</ns1:name>
                        <ns1:sequence>{ $count) }</ns1:sequence>
</ns1:books>


Instead we can use the following approach.

While declaring the for loop also declare a position variable.

Use this position variable in the place of count as follows


 for $record at $position in $collection/books
                   return
                     <ns1:books>
                        <ns1:name>{ $record/name }</ns1:name>
                        <ns1:sequence>{ $position) }</ns1:sequence>
   </ns1:books>

1 comment: