Peebl Peebl - 22 days ago 6
HTML Question

Separating same kind of element by a comma

I have this xquery for a collection of books, which individually have 1 or more fagfelt(topics) each. When i run my query all the topics are grouped up in one cell of the table (I want this), but they are not easily separated

let $books := (doc("oblig3.xml")/b√łker/bok)
return
<html>
<head>
</head>
<body>
<table border="1">
<tr>Fagfelt</tr><hr/>
<tr><td><b>Bok Title</b></td>
<td><b>Forfatter</b></td>
<td colspan="3"><b>Fagfelt</b></td>
</tr>
{
for $x in $books
order by $x/tittle
return <tr>
<td>{data($x/tittle)}</td>
<td>{data($x/forfatter)}</td>
<td>{data($x/fagfelt)}</td>
</tr>
}
</table>
</body>
</html>


Example of a return I get is -

<td>Filosofi Kunnskapsrepresentasjon Kunstig Intelligens Programmering</td>


Which is 4 topics in one, not very easy to read. How can I separate these and make it look more like

<td>Filosofi, Kunnskapsrepresentasjon, Kunstig Intelligens, Programmering</td>


Preferably within the same cell, I have tried just listing them with

{data($x/fagfelt[1...4]/text())},


And doing the separation manually, but that just leaves a lot of commas at the end of books with just 1 topic.

wst wst
Answer

When you serialize a sequence to a string in XQuery, the defined behavior is to return a space-delimited list. However, if you want to use a custom delimiter, use fn:string-join():

fn:string-join($x/fagfelt, ', ')

From the W3C specification:

Each enclosed expression is converted to a string as follows:

a. Atomization is applied to the value of the enclosed expression, converting it to a sequence of atomic values.

b. If the result of atomization is an empty sequence, the result is the zero-length string. Otherwise, each atomic value in the atomized sequence is cast into a string.

c. The individual strings resulting from the previous step are merged into a single string by concatenating them with a single space character between each pair.

Comments