XQuery: how to properly append , in for loop

耗尽温柔 提交于 2019-12-23 08:47:34

问题


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?


回答1:


<PhoneNumberList>
{
    string-join($c//PhoneNumber, ", ")
}
</PhoneNumberList>



回答2:


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>



回答3:


Ok, something like this should return the first element as-is and the rest with prepended ", "

<PhoneNumberList>
{
  for $phone in $c//PhoneNumber[0]
  return $phone
  for $phone in $c//PhoneNumber[position()>0]
  return concat(", ", $phone)
}
</PhoneNumberList>



回答4:


What about this?

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


来源:https://stackoverflow.com/questions/1739479/xquery-how-to-properly-append-in-for-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!