开发者

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 lik开发者_运维知识库e

 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


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...


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, "/"))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜