Developing Scripts to convert Csv file into xml using Groovy
Step1: Create a sample groovy file
File name : Csv2xml.groovy
/*
* Here the Code
*/
//Csv2xml.groovy
package com.groovy.sample
import groovy.xml.StreamingMarkupBuilder
import groovy.xml.XmlUtil
//csvfile to xml
class Csv2xml {
static void main(args){
def csvdata = []
new File("csv2xml.csv").eachLine { line ->
csvdata << line.split(',')
}
def headers = csvdata[0]
def dataRows = csvdata[1..-1]
def xml = new groovy.xml.MarkupBuilder()
// write 'root' element
xml.root {
dataRows.eachWithIndex { dataRow, index ->
// write 'entry' element with 'id' attribute
entry(id:index+1) {
headers.eachWithIndex { heading, i ->
// write each heading with associated content
"${heading}"(dataRow[i])
}
}
}
}
}
}
Step2:
After above .groovy code then we need to create one csv file. The file name it seems like what we have mentioned in groovy code like "csv2xml.csv"
create csv file :
Job,Type,Cntr Number,Date,Booking Ref,Commodity,Weight,Special Instructions
JOB0001,Circle,12,31/09/2013,Book0001,1,100,Carry
software engine ,new ,36,31/09/2013,Book0002,5,68,nan
After creating csv file then execute the Csv2xml.groovy class file
output:
<root>
<entry id='1'>
<Job>JOB0001</Job>
<Type>Circle</Type>
<Cntr Number>12</Cntr Number>
<Date>31/09/2013</Date>
<Booking Ref>Book0001</Booking Ref>
<Commodity>1</Commodity>
<Weight>100</Weight>
<Special Instructions>Carry</Special Instructions>
</entry>
<entry id='2'>
<Job>software engine </Job>
<Type>new </Type>
<Cntr Number>36</Cntr Number>
<Date>31/09/2013</Date>
<Booking Ref>Book0002</Booking Ref>
<Commodity>5</Commodity>
<Weight>68</Weight>
<Special Instructions>nan</Special Instructions>
</entry>
</root>
No comments:
Post a Comment