XQuery/顯示列表
外觀
< XQuery
您在 XML 結構中有一個專案列表,您想在輸出字串中顯示一個用逗號分隔的專案值列表。
XQuery 提供了 "string-join()" 函式,它可以接受一個專案序列和一個分隔符字串,並建立一個帶有分隔符的輸出字串,這些分隔符位於每個專案之間。函式的格式為:string-join(nodeset, separator),其中 nodeset 是一個節點列表,而 separator 是您想用來分隔值的字串。
xquery version "1.0";
let $tags :=
<tags>
<tag>x</tag>
<tag>y</tag>
<tag>z</tag>
<tag>d</tag>
</tags>
return
<results>
<comma-separated-values>{
string-join($tags/tag, ',')
}</comma-separated-values>
</results>
<results>
<comma-separated-values>x,y,z,d</comma-separated-values>
</results>
我們將使用兩個 "string-join()" 函式,一個用於所有行,另一個用於每一行。我們將建立一個大型字串,然後使用 "response:stream()" 函式返回結果。
xquery version "1.0";
declare option exist:serialize "method=text media-type=text/csv omit-xml-declaration=yes";
(: The newline character used as a separator between lines :)
let $nl := " "
let $input :=
<rows>
<row>
<c1>Row1 Col1</c1>
<c2>Row1 Col2</c2>
<c3>Row1 Col3</c3>
<c4>Row1 Col4</c4>
</row>
<row>
<c1>Row2 Col1</c1>
<c2>Row2 Col2</c2>
<c3>Row2 Col3</c3>
<c4>Row2 Col4</c4>
</row>
<row>
<c1>Row3 Col1</c1>
<c2>Row3 Col2</c2>
<c3>Row3 Col3</c3>
<c4>Row3 Col4</c4>
</row>
<row>
<c1>Row4 Col1</c1>
<c2>Row4 Col2</c2>
<c3>Row4 Col3</c3>
<c4>Row2 Col4</c4>
</row>
</rows>
(: we construct a single string that has all the newlines and commas in the right places :)
let $file-as-csv-string :=
string-join(
for $row in $input//row
return
string-join(
for $col in $row/*
return
$col/text()
, ',')
, $nl)
(: set the HTTP response headers with the content type and file name :)
let $set-content-type := response:set-header('Content-Type', 'text/csv')
let $set-file-name := response:set-header('Content-Disposition', 'attachment; filename="my-table.csv"')
(: There is no documentation on what the stream options are.
http://exist-db.org/exist/apps/fundocs/view.html?uri=http://exist-db.org/xquery/response&location=java:org.exist.xquery.functions.response.ResponseModule
:)
return response:stream($file-as-csv-string, '')
返回值
Row1 Col1,Row1 Col2,Row1 Col3,Row1 Col4 Row2 Col1,Row2 Col2,Row2 Col3,Row2 Col4 Row3 Col1,Row3 Col2,Row3 Col3,Row3 Col4 Row4 Col1,Row4 Col2,Row4 Col3,Row4 Col4
"string-join()" 函式接受兩個引數,第一個是待連線的字串序列,第二個是分隔符。