Any better way to export double quote csv data from string object in Xquery

Viewed 57

It is common to export list of strings as double quote csv format in log file with Xquery for ML.

I wonder whether there is better way to do so from the list of the strings. Currently I have to use a lot of fn:concat('"', $value , '"') block to do it. It becomes difficult to read if there is a long list of values to process.

Below is the current code for a simple demo case.

xquery version "1.0-ml";

let $values := ('string 1', 'string 2', 'string N')

return fn:string-join( $values ! fn:concat('"', . , '"'), ',')

The expected output is "string 1","string 2","string N"

2 Answers

If you want to wrap every value in quotes, you could simplify slightly to something like the below.

xquery version "1.0-ml";

let $values := ('string 1', 'string 2', 'string N')

return '"' || fn:string-join($values, '","') || '"'

With generic XQuery 3.1, you can elegantly build up the CSV values using the arrow operator:

xquery version "3.1";

let $values := ('string 1', 'string 2', 'string N')
return
    $values
    => for-each( function($value) { '"' || $value || '"' } )
    => string-join(",")

Depending on the content of your values, you might need to apply some escaping - e.g., of commas or quotation marks.

This could easily be wrapped into a function, e.g., local:create-csv-row($values).

Related