I need to convert a csv file to xml in the following format:
The input csv is
scott,male,26,doctor
ryan,male,20,student
laura,female,30,lawyer
The resulting xml should be
<root>
<criteria name="scott" sex = "male" age = "26" profession = "doctor"/>
<criteria name="ryan" sex = "male" age = "20" profession = "student"/>
<criteria name="laura" sex = "female" age = "30" profession = "lawyer"/>
<root/>
and in the csv if any field is missing like profession,
laura,female,30
the resulting xml should be
<criteria name="laura" sex = "female" age = "30"/>
if the csv is :
laura,female,,lawyer
it produces
<criteria name="laura" sex = "female" age = "" profession = "lawyer"/>
where as i want the xml to be
<criteria name="laura" sex = "female" profession = "lawyer"/>
Can some one help me out with the code to do that in groovy?
The code i am using is
CommonsMultipartFile multiPartFile=fileList.first()
params.type = 'text/csv'
if(CSV_MIME_TYPE.contains(params.type)){
InputStream inputStream= multiPartFile.getInputStream()
def writer=new StringWriter()
def xmlBuilder= new MarkupBuilder(writer)
xmlBuilder.setDoubleQuotes(true)
xmlBuilder.root(){
inputStream.eachLine{ line->
def a,b,c,d,e,f,g
(a,b,c,d) = line.split(',',-1)
criteria(name:a,sex:b,age:c,profession:d)
}