Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XQuery: how to properly append , in for loop

Tags:

xquery

So I have xml data like this:

  <PhoneNumber>213-512-7457</PhoneNumber>
  <PhoneNumber>213-512-7465</PhoneNumber>

and with this XQuery:

<PhoneNumberList>
{
  for $phone in $c//PhoneNumber
  let $phoneStr := ""
  return concat($phoneStr, $phone) 
}
</PhoneNumberList>

I get:

<PhoneNumberList>213-512-7457213-512-7465</PhoneNumberList>

But I actually want:

<PhoneNumberList>213-512-7457, 213-512-7465</PhoneNumberList>

Could someone shed some light on how to do this?

like image 384
sivabudh Avatar asked Nov 16 '09 00:11

sivabudh


2 Answers

<PhoneNumberList>
{
    string-join($c//PhoneNumber, ", ")
}
</PhoneNumberList>
like image 107
asdf Avatar answered Oct 21 '22 04:10

asdf


There seems to be a lot of confusion with variables in XQuery. A let expression creates a new variable each time it is evaluated, so the "procedural" approaches below will not work.

Whilst the string-join solution is the best in your case, the correct way to write this "manually" is with a recursive function:

declare function local:join-numbers($numbers)
{
  concat($numbers[1], ", ", local:join-numbers(substring($numbers,2)))
};

<PhoneNumberList>
{
  local:joinNumbers($c//PhoneNumber)
}
</PhoneNumberList>
like image 1
Oliver Hallam Avatar answered Oct 21 '22 03:10

Oliver Hallam