English 中文(简体)
XQuery: how to properly append , in for loop
原标题:
  • 时间:2009-11-16 00:32:33
  •  标签:
  • 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?

最佳回答
<PhoneNumberList>
{
    string-join($c//PhoneNumber, ", ")
}
</PhoneNumberList>
问题回答

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>

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>

What about this?

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




相关问题
XQuery, fn:id and BD eXist

Does "fn:id" function return IDREFS when it is used in a FLOWER xquery with eXists database? I can t get any example... :(

SQL Server xQuery return NULL instead of empty

So in this example I m trying to return a NULL instead of an empty nvarchar for element2 and element3. I can t seem to find an answer to this anywhere, or if it s even possible. I know I can check ....

Does QExo XQuery string-join work?

When I run string-join, I get a weird output like this: <clinic> <Name>Olive Street Pediatrics</Name> <Address>1500 Olive St, Los Angeles, CA 90015</Address> <...

XQuery: how to properly append , in for loop

So I have xml data like this: <PhoneNumber>213-512-7457</PhoneNumber> <PhoneNumber>213-512-7465</PhoneNumber> and with this XQuery: <PhoneNumberList> { for $...

Filter SQL queries on the XML column using XPath/XQuery

I m having a table with one XML column. I d like to filter out the rows where a specific attribute in the XML match a string, essentially doing a WHERE or HAVING. The table looks something like this ...

热门标签