user851380
user851380

Reputation: 339

how to build string iteratively in xquery

I need the xquery structure which is the same with java code

   string temp
   for(int i=0,i<string[].length,i++)
   temp=temp+string[i]

for example, in xquery, I have string /a/b/c I need to something like

 let $temp:=""
   for $x in tokenize(string,'/')
   $temp=concat($temp,$x)
   return $temp

and it should return the following at each iterate

   a
   ab
   abc

but somehow it seams that this statement $temp=concat($temp,$x) is not working. so what's the right syntax to do this? Thanks in advance

Upvotes: 2

Views: 3106

Answers (2)

Dennis M&#252;nkle
Dennis M&#252;nkle

Reputation: 5071

I think, you need to get the notion of declarative programming. You are trying to tell the processor what to do (like you would do in java) instead of describing the overall result. For example, if you don't use the scripting extension (which is only supported by some processors, e.g. zorba) you cannot use assignments the way you would use them in java. Think of it as the complete query describing one resulting document.

This stuff is hard to get in the beginning, but it brings huge benefits in the end (productivity, robustness, performance).

I would translate your imperative pseudo code into this one-liner:

string-join(tokenize("/a/b/c",'/'))

You can test it on try.zorba-xquery.com. I really hope this helps. Sorry, if this is not the answer you were looking for...

Upvotes: 2

Dave Cassel
Dave Cassel

Reputation: 8422

The $temp=conct($temp, $x) doesn't accumulate because in XQuery, that's a new variable each time through the loop. Try the following (tested in MarkLogic but uses all standard syntax):

declare function local:build($prefix, $tokens)
{
  if (fn:exists($tokens)) then
    let $str := fn:concat($prefix, $tokens[1])
    return ( 
      $str,
      local:build($str, fn:subsequence($tokens, 2))
    )
  else ()
};

let $string := "/a/b/c"
return local:build("", fn:tokenize($string, "/"))

Upvotes: 0

Related Questions