parsing csv files with groovy

We have a piece of software that insists on generating a type of csv file containing multiple datasets. I'm currently turning this into XML to make it easier to process (funny that, people seem to have a downer on xml most of the time). I want to parse the csv without knowing what the columns will be, plus they can be speechmark delimitted and maybe contain carriage returns. Anyway, it seems easy to start with and then gets more and more involved. Let's face it, life is too short to write a full parser for myself. I did a bit of research and took the opportunity to try it out in groovy. My latest version uses a groovy wrapper of

UPDATE: my good friend and ex-colleague @nugsie suggested a MarkupBuilder….


import com.xlson.groovycsv.CsvParser
import groovy.xml.MarkupBuilder

def csv = '''field_one,field_two,field_three

def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
def data = new CsvParser().parse(csv)
xml.records() {
   data.each { line ->
     feature() {
       line.columns.each { columnName, index ->

writer.toString() '''

output from which is:

<?xml version="1.0" encoding="UTF-8"?> <records>   <Feature>     <field_one>ay</field_one>     <field_two>be"e</field_two>     <field_three>sea</field_three>   </Feature>   <Feature>     <field_one>ay</field_one>     <field_two>bee multiline</field_two>     <field_three>sea</field_three>   </Feature> </records>


It's All In The Game blog (c) 2005-16 by Jez Nicholson