How do I convert a CSV into an XML file in Java?
string,float1,float2,integer
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
"${heading}"(dataRow[i])
}
}
}
}
<root>
<entry id="1">
<string>hello world</string>
<float1>1.0</float1>
<float2>3.3</float2>
<integer>4</integer>
</entry>
<entry id="2">
<string>goodbye world</string>
<float1>1e9</float1>
<float2>-3.3</float2>
<integer>45</integer>
</entry>
<entry id="3">
<string>hello again</string>
<float1>-1</float1>
<float2>23.33</float2>
<integer>456</integer>
</entry>
<entry id="4">
<string>hello world 3</string>
<float1>1.40</float1>
<float2>34.83</float2>
<integer>4999</integer>
</entry>
<entry id="5">
<string>hello 2 world</string>
<float1>9981.05</float1>
<float2>43.33</float2>
<integer>444</integer>
</entry>
</root>
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:
- Is Object Property accessible from within object method?
- What is the meaning of the type safety warning in some Java generics casts?
- What is the difference between Int and Integer in Java and C#?
- I would like to import CSV file to strongly typed data structure in.Net. However the only exception is in one case. Is there any method to import CSV file?
- How can I add custom button in Java?
- What do you need to do for XML files?
- What are the different methods to parse strings in Java?
- How do I get the inner xml of a XElement?
- Is it illegal to throw a Null parameter without a NullPointerException for that parameter?
- What tools are good for code analysis?
- How do I read from a file that is actually being written to?
- Why is Java autoboxing used only for method invocations and not classes. The type has a class and an operator and the methods are autoboxed, doesn't this mean revocations of the method can be invoked?
- What is CSV string handling?
- How can I use Java webstart multiple libraries?
- Is it better to use widening vs autoboxing?