XQuery/Parsing CSV

From Wikibooks, open books for an open world
Jump to: navigation, search


You want to parse a file of comma-separated values (CSV) text into an xml structure or you have a flat file with very similar line/field structure that you want to convert into XML format.


We will use the tokenize($input, '\n') function to break the input file into separate lines. We will then use the tokenize($input, ',') function to parse each line into separate fields.

Basic Example[edit]

xquery version "1.0";

let $title := 'XQuery CSV Parser'

let $csv-input-sample :=

let $lines := tokenize($csv-input-sample, '\n')

  for $line in $lines
  let $fields := tokenize($line, ',')
    for $field in $fields

Sample Output[edit]


Example With Data Dictionary in Row 1[edit]

This second example will use the first row of the CSV file as a data dictionary of the element names for each column of each row.

let $csv :=

let $lines := tokenize($csv, '\n')
let $head := tokenize($lines[1], ',')
let $body := remove($lines, 1)
            for $line in $body
            let $fields := tokenize($line, ',')
                        for $key at $pos in $head
                        let $value := $fields[$pos]
                            element { $key } { $value }

We will receive below result (tested with eXide in eXist 2.0):


Beware though, that this requires the very strict input format proposed. In practice CSV can look quite different.

Adding Configuration File Options[edit]

Many times you have a family of CSV files that all may have very similar options for import. In this case it is useful to be able to pass a series of configuration parameters to a single XQuery function. These configuration parameters include:

  1. What the field delimiter is (comma is the default)
  2. The element name of the root node
  3. The element name of each line or row
  1. If each field could be wrapped in quotes

You can then pass this configuration file to your XQuery function:

  import-lib:flat-file-import($input-file, $config)


Zorba CSV importer