The best resources for developers

How do I convert a CSV into an XML file in Java?

hello world,1.0,3.3,4
goodbye world,1e9,-3.3,45
hello again,-1,23.33,456
hello world 3,1.40,34.83,4999
hello 2 world,9981.05,43.33,444
#!/usr/bin/env groovy

def csvdata = []
new File("test.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
  <entry id="1">
    <string>hello world</string>
  <entry id="2">
    <string>goodbye world</string>
  <entry id="3">
    <string>hello again</string>
  <entry id="4">
    <string>hello world 3</string>
  <entry id="5">
    <string>hello 2 world</string>

Tags: java xml csv data-conversion

Source: By A Salim as answer to the question

This code snippet was collected from stackoverflow, and is licensed under CC BY-SA 3.0

Related code-snippets: