<p>Is there an existing application or library in <em>Java</em> which will allow me to convert a <code>CSV</code> data file to <code>XML</code> file?  </p>

<p>The <code>XML</code> tags would be provided through possibly the first row containing column headings.</p>

[{'answer_id': 133, 'author': 'saint_groceon', 'author_id': 59, 'author_profile': 'https://Stackoverflow.com/users/59', 'pm_score': 2, 'selected': False, 'text': '<p>This may be too basic or limited of a solution, but couldn\'t you do a <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)" rel="nofollow noreferrer"><code>String.split()</code></a> on each line of the file, remembering the result array of the first line to generate the XML, and just spit each line\'s array data out with the proper XML elements padding each iteration of a loop?</p>\n'}, {'answer_id': 183, 'author': 'svrist', 'author_id': 86, 'author_profile': 'https://Stackoverflow.com/users/86', 'pm_score': 7, 'selected': True, 'text': '<p>Maybe this might help: <a href="http://jsefa.sourceforge.net/quick-tutorial.html" rel="noreferrer">JSefa</a></p>\n\n<p>You can read CSV file with this tool and serialize it to XML.</p>\n'}, {'answer_id': 190, 'author': 'Ryan Fox', 'author_id': 55, 'author_profile': 'https://Stackoverflow.com/users/55', 'pm_score': 4, 'selected': False, 'text': "<p>I don't understand why you would want to do this. It sounds almost like cargo cult coding.</p>\n\n<p>Converting a CSV file to XML doesn't add any value. Your program is already reading the CSV file, so arguing that you need XML doesn't work.</p>\n\n<p>On the other hand, reading the CSV file, doing <em>something</em> with the values, and then serializing to XML does make sense (well, as much as using XML can make sense... ;)) but you would supposedly already have a means of serializing to XML.</p>\n"}, {'answer_id': 540, 'author': 'Matt', 'author_id': 154, 'author_profile': 'https://Stackoverflow.com/users/154', 'pm_score': 3, 'selected': False, 'text': "<p>As far as I know, there's no ready-made library to do this for you, but producing a tool capable of translating from CSV to XML should only require you to write a crude CSV parser and hook up JDOM (or your XML Java library of choice) with some glue code.</p>\n"}, {'answer_id': 939, 'author': 'Claude Houle', 'author_id': 244, 'author_profile': 'https://Stackoverflow.com/users/244', 'pm_score': 3, 'selected': False, 'text': '<p>There is nothing I know of that can do this without you at least writing a little bit of code... You will need 2 separate library:</p>\n\n<ul>\n<li>A CSV Parser Framework </li>\n<li>An XML Serialization Framework</li>\n</ul>\n\n<p>The CSV parser I would recommend (unless you want to have a little bit of fun to write your own CSV Parser) is OpenCSV (A SourceForge Project for parsing CSV Data)</p>\n\n<p>The XML Serialization Framework should be something that can scale in case you want to transform large (or huge) CSV file to XML: My recommendation is the Sun Java Streaming XML Parser Framework (See <a href="https://sjsxp.java.net/" rel="noreferrer">here</a>) which allows pull-parsing AND serialization.</p>\n'}, {'answer_id': 6726, 'author': 'Anthony Cramp', 'author_id': 488, 'author_profile': 'https://Stackoverflow.com/users/488', 'pm_score': 5, 'selected': False, 'text': '<p>I know you asked for Java, but this strikes me as a task well suited to a scripting language. Here is a quick (very simple) solution written in Groovy.</p>\n\n<p><strong>test.csv</strong></p>\n\n<pre><code>string,float1,float2,integer\nhello world,1.0,3.3,4\ngoodbye world,1e9,-3.3,45\nhello again,-1,23.33,456\nhello world 3,1.40,34.83,4999\nhello 2 world,9981.05,43.33,444\n</code></pre>\n\n<p><strong>csvtoxml.groovy</strong></p>\n\n<pre><code>#!/usr/bin/env groovy\n\ndef csvdata = []\nnew File("test.csv").eachLine { line -&gt;\n    csvdata &lt;&lt; line.split(\',\')\n}\n\ndef headers = csvdata[0]\ndef dataRows = csvdata[1..-1]\n\ndef xml = new groovy.xml.MarkupBuilder()\n\n// write \'root\' element\nxml.root {\n    dataRows.eachWithIndex { dataRow, index -&gt;\n        // write \'entry\' element with \'id\' attribute\n        entry(id:index+1) {\n            headers.eachWithIndex { heading, i -&gt;\n                // write each heading with associated content\n                "${heading}"(dataRow[i])\n            }\n        }\n    }\n}\n</code></pre>\n\n<p>Writes the following XML to stdout:</p>\n\n<pre><code>&lt;root&gt;\n  &lt;entry id=\'1\'&gt;\n    &lt;string&gt;hello world&lt;/string&gt;\n    &lt;float1&gt;1.0&lt;/float1&gt;\n    &lt;float2&gt;3.3&lt;/float2&gt;\n    &lt;integer&gt;4&lt;/integer&gt;\n  &lt;/entry&gt;\n  &lt;entry id=\'2\'&gt;\n    &lt;string&gt;goodbye world&lt;/string&gt;\n    &lt;float1&gt;1e9&lt;/float1&gt;\n    &lt;float2&gt;-3.3&lt;/float2&gt;\n    &lt;integer&gt;45&lt;/integer&gt;\n  &lt;/entry&gt;\n  &lt;entry id=\'3\'&gt;\n    &lt;string&gt;hello again&lt;/string&gt;\n    &lt;float1&gt;-1&lt;/float1&gt;\n    &lt;float2&gt;23.33&lt;/float2&gt;\n    &lt;integer&gt;456&lt;/integer&gt;\n  &lt;/entry&gt;\n  &lt;entry id=\'4\'&gt;\n    &lt;string&gt;hello world 3&lt;/string&gt;\n    &lt;float1&gt;1.40&lt;/float1&gt;\n    &lt;float2&gt;34.83&lt;/float2&gt;\n    &lt;integer&gt;4999&lt;/integer&gt;\n  &lt;/entry&gt;\n  &lt;entry id=\'5\'&gt;\n    &lt;string&gt;hello 2 world&lt;/string&gt;\n    &lt;float1&gt;9981.05&lt;/float1&gt;\n    &lt;float2&gt;43.33&lt;/float2&gt;\n    &lt;integer&gt;444&lt;/integer&gt;\n  &lt;/entry&gt;\n&lt;/root&gt;\n</code></pre>\n\n<p>However, the code does very simple parsing (not taking into account quoted or escaped commas) and it does not account for possible absent data.</p>\n'}, {'answer_id': 21413, 'author': 'Martin Klinke', 'author_id': 1793, 'author_profile': 'https://Stackoverflow.com/users/1793', 'pm_score': 4, 'selected': False, 'text': '<p>This solution does not need any CSV or XML libraries and, I know, it does not handle any illegal characters and encoding issues, but you might be interested in it as well, provided your CSV input does not break the above mentioned rules.</p>\n\n<p><strong>Attention:</strong> You should not use this code unless you know what you do or don\'t have the chance to use a further library (possible in some bureaucratic projects)... Use a StringBuffer for older Runtime Environments...</p>\n\n<p>So here we go:</p>\n\n<pre><code>BufferedReader reader = new BufferedReader(new InputStreamReader(\n        Csv2Xml.class.getResourceAsStream("test.csv")));\nStringBuilder xml = new StringBuilder();\nString lineBreak = System.getProperty("line.separator");\nString line = null;\nList&lt;String&gt; headers = new ArrayList&lt;String&gt;();\nboolean isHeader = true;\nint count = 0;\nint entryCount = 1;\nxml.append("&lt;root&gt;");\nxml.append(lineBreak);\nwhile ((line = reader.readLine()) != null) {\n    StringTokenizer tokenizer = new StringTokenizer(line, ",");\n    if (isHeader) {\n        isHeader = false;\n        while (tokenizer.hasMoreTokens()) {\n            headers.add(tokenizer.nextToken());\n        }\n    } else {\n        count = 0;\n        xml.append("\\t&lt;entry id=\\"");\n        xml.append(entryCount);\n        xml.append("\\"&gt;");\n        xml.append(lineBreak);\n        while (tokenizer.hasMoreTokens()) {\n            xml.append("\\t\\t&lt;");\n            xml.append(headers.get(count));\n            xml.append("&gt;");\n            xml.append(tokenizer.nextToken());\n            xml.append("&lt;/");\n            xml.append(headers.get(count));\n            xml.append("&gt;");\n            xml.append(lineBreak);\n            count++;\n        }\n        xml.append("\\t&lt;/entry&gt;");\n        xml.append(lineBreak);\n        entryCount++;\n    }\n}\nxml.append("&lt;/root&gt;");\nSystem.out.println(xml.toString());\n</code></pre>\n\n<p>The input test.csv (stolen from another answer on this page):</p>\n\n<pre><code>string,float1,float2,integer\nhello world,1.0,3.3,4\ngoodbye world,1e9,-3.3,45\nhello again,-1,23.33,456\nhello world 3,1.40,34.83,4999\nhello 2 world,9981.05,43.33,444\n</code></pre>\n\n<p>The resulting output:</p>\n\n<pre><code>&lt;root&gt;\n    &lt;entry id="1"&gt;\n        &lt;string&gt;hello world&lt;/string&gt;\n        &lt;float1&gt;1.0&lt;/float1&gt;\n        &lt;float2&gt;3.3&lt;/float2&gt;\n        &lt;integer&gt;4&lt;/integer&gt;\n    &lt;/entry&gt;\n    &lt;entry id="2"&gt;\n        &lt;string&gt;goodbye world&lt;/string&gt;\n        &lt;float1&gt;1e9&lt;/float1&gt;\n        &lt;float2&gt;-3.3&lt;/float2&gt;\n        &lt;integer&gt;45&lt;/integer&gt;\n    &lt;/entry&gt;\n    &lt;entry id="3"&gt;\n        &lt;string&gt;hello again&lt;/string&gt;\n        &lt;float1&gt;-1&lt;/float1&gt;\n        &lt;float2&gt;23.33&lt;/float2&gt;\n        &lt;integer&gt;456&lt;/integer&gt;\n    &lt;/entry&gt;\n    &lt;entry id="4"&gt;\n        &lt;string&gt;hello world 3&lt;/string&gt;\n        &lt;float1&gt;1.40&lt;/float1&gt;\n        &lt;float2&gt;34.83&lt;/float2&gt;\n        &lt;integer&gt;4999&lt;/integer&gt;\n    &lt;/entry&gt;\n    &lt;entry id="5"&gt;\n        &lt;string&gt;hello 2 world&lt;/string&gt;\n        &lt;float1&gt;9981.05&lt;/float1&gt;\n        &lt;float2&gt;43.33&lt;/float2&gt;\n        &lt;integer&gt;444&lt;/integer&gt;\n    &lt;/entry&gt;\n&lt;/root&gt;\n</code></pre>\n'}, {'answer_id': 53547, 'author': 'Laurent K', 'author_id': 2965, 'author_profile': 'https://Stackoverflow.com/users/2965', 'pm_score': 6, 'selected': False, 'text': '<p>As the others above, I don\'t know any one-step way to do that, but if you are ready to use very simple external libraries, I would suggest:</p>\n\n<p><a href="http://opencsv.sourceforge.net/" rel="noreferrer">OpenCsv</a> for parsing CSV (small, simple, reliable and easy to use)</p>\n\n<p><strong>Xstream</strong> to parse/serialize XML (very very easy to use, and creating fully human readable xml)</p>\n\n<p>Using the same sample data as above, code would look like:</p>\n\n<pre><code>package fr.megiste.test;\n\nimport java.io.FileReader;\nimport java.io.FileWriter;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport au.com.bytecode.opencsv.CSVReader;\n\nimport com.thoughtworks.xstream.XStream;\n\npublic class CsvToXml {     \n\n    public static void main(String[] args) {\n\n        String startFile = "./startData.csv";\n        String outFile = "./outData.xml";\n\n        try {\n            CSVReader reader = new CSVReader(new FileReader(startFile));\n            String[] line = null;\n\n            String[] header = reader.readNext();\n\n            List out = new ArrayList();\n\n            while((line = reader.readNext())!=null){\n                List&lt;String[]&gt; item = new ArrayList&lt;String[]&gt;();\n                    for (int i = 0; i &lt; header.length; i++) {\n                    String[] keyVal = new String[2];\n                    String string = header[i];\n                    String val = line[i];\n                    keyVal[0] = string;\n                    keyVal[1] = val;\n                    item.add(keyVal);\n                }\n                out.add(item);\n            }\n\n            XStream xstream = new XStream();\n\n            xstream.toXML(out, new FileWriter(outFile,false));\n\n        } catch (Exception e) {\n            // TODO Auto-generated catch block\n            e.printStackTrace();\n        }\n    }\n}\n</code></pre>\n\n<p>Producing the following result:\n(Xstream allows very fine tuning of the result...)</p>\n\n<pre><code>&lt;list&gt;\n  &lt;list&gt;\n    &lt;string-array&gt;\n      &lt;string&gt;string&lt;/string&gt;\n      &lt;string&gt;hello world&lt;/string&gt;\n    &lt;/string-array&gt;\n    &lt;string-array&gt;\n      &lt;string&gt;float1&lt;/string&gt;\n      &lt;string&gt;1.0&lt;/string&gt;\n    &lt;/string-array&gt;\n    &lt;string-array&gt;\n      &lt;string&gt;float2&lt;/string&gt;\n      &lt;string&gt;3.3&lt;/string&gt;\n    &lt;/string-array&gt;\n    &lt;string-array&gt;\n      &lt;string&gt;integer&lt;/string&gt;\n      &lt;string&gt;4&lt;/string&gt;\n    &lt;/string-array&gt;\n  &lt;/list&gt;\n  &lt;list&gt;\n    &lt;string-array&gt;\n      &lt;string&gt;string&lt;/string&gt;\n      &lt;string&gt;goodbye world&lt;/string&gt;\n    &lt;/string-array&gt;\n    &lt;string-array&gt;\n      &lt;string&gt;float1&lt;/string&gt;\n      &lt;string&gt;1e9&lt;/string&gt;\n    &lt;/string-array&gt;\n    &lt;string-array&gt;\n      &lt;string&gt;float2&lt;/string&gt;\n      &lt;string&gt;-3.3&lt;/string&gt;\n    &lt;/string-array&gt;\n    &lt;string-array&gt;\n      &lt;string&gt;integer&lt;/string&gt;\n      &lt;string&gt;45&lt;/string&gt;\n    &lt;/string-array&gt;\n  &lt;/list&gt;\n  &lt;list&gt;\n    &lt;string-array&gt;\n      &lt;string&gt;string&lt;/string&gt;\n      &lt;string&gt;hello again&lt;/string&gt;\n    &lt;/string-array&gt;\n    &lt;string-array&gt;\n      &lt;string&gt;float1&lt;/string&gt;\n      &lt;string&gt;-1&lt;/string&gt;\n    &lt;/string-array&gt;\n    &lt;string-array&gt;\n      &lt;string&gt;float2&lt;/string&gt;\n      &lt;string&gt;23.33&lt;/string&gt;\n    &lt;/string-array&gt;\n    &lt;string-array&gt;\n      &lt;string&gt;integer&lt;/string&gt;\n      &lt;string&gt;456&lt;/string&gt;\n    &lt;/string-array&gt;\n  &lt;/list&gt;\n  &lt;list&gt;\n    &lt;string-array&gt;\n      &lt;string&gt;string&lt;/string&gt;\n      &lt;string&gt;hello world 3&lt;/string&gt;\n    &lt;/string-array&gt;\n    &lt;string-array&gt;\n      &lt;string&gt;float1&lt;/string&gt;\n      &lt;string&gt;1.40&lt;/string&gt;\n    &lt;/string-array&gt;\n    &lt;string-array&gt;\n      &lt;string&gt;float2&lt;/string&gt;\n      &lt;string&gt;34.83&lt;/string&gt;\n    &lt;/string-array&gt;\n    &lt;string-array&gt;\n      &lt;string&gt;integer&lt;/string&gt;\n      &lt;string&gt;4999&lt;/string&gt;\n    &lt;/string-array&gt;\n  &lt;/list&gt;\n  &lt;list&gt;\n    &lt;string-array&gt;\n      &lt;string&gt;string&lt;/string&gt;\n      &lt;string&gt;hello 2 world&lt;/string&gt;\n    &lt;/string-array&gt;\n    &lt;string-array&gt;\n      &lt;string&gt;float1&lt;/string&gt;\n      &lt;string&gt;9981.05&lt;/string&gt;\n    &lt;/string-array&gt;\n    &lt;string-array&gt;\n      &lt;string&gt;float2&lt;/string&gt;\n      &lt;string&gt;43.33&lt;/string&gt;\n    &lt;/string-array&gt;\n    &lt;string-array&gt;\n      &lt;string&gt;integer&lt;/string&gt;\n      &lt;string&gt;444&lt;/string&gt;\n    &lt;/string-array&gt;\n  &lt;/list&gt;\n&lt;/list&gt;\n</code></pre>\n'}, {'answer_id': 74018, 'author': 'Arne Burmeister', 'author_id': 12890, 'author_profile': 'https://Stackoverflow.com/users/12890', 'pm_score': 2, 'selected': False, 'text': '<p>For the CSV Part, you may use <a href="https://github.com/aburmeis/decs" rel="nofollow noreferrer">my little open source library</a></p>\n'}, {'answer_id': 144768, 'author': 'kolrie', 'author_id': 14540, 'author_profile': 'https://Stackoverflow.com/users/14540', 'pm_score': 4, 'selected': False, 'text': '<p>I have an opensource framework for working with CSV and flat files in general. Maybe it\'s worth looking: <a href="http://jfilehelpers.com" rel="noreferrer" title="JFileHelpers">JFileHelpers</a>.</p>\n\n<p>With that toolkit you can write code using beans, like:</p>\n\n<pre><code>@FixedLengthRecord()\npublic class Customer {\n    @FieldFixedLength(4)\n    public Integer custId;\n\n    @FieldAlign(alignMode=AlignMode.Right)\n    @FieldFixedLength(20)\n    public String name;\n\n    @FieldFixedLength(3)\n    public Integer rating;\n\n    @FieldTrim(trimMode=TrimMode.Right)\n    @FieldFixedLength(10)\n    @FieldConverter(converter = ConverterKind.Date, \n    format = "dd-MM-yyyy")\n    public Date addedDate;\n\n    @FieldFixedLength(3)\n    @FieldOptional\n    public String stockSimbol;  \n}\n</code></pre>\n\n<p>and then just parse your text files using:</p>\n\n<pre><code>FileHelperEngine&lt;Customer&gt; engine = \n    new FileHelperEngine&lt;Customer&gt;(Customer.class); \nList&lt;Customer&gt; customers = \n    new ArrayList&lt;Customer&gt;();\n\ncustomers = engine.readResource(\n    "/samples/customers-fixed.txt");\n</code></pre>\n\n<p>And you\'ll have a collection of parsed objects.</p>\n\n<p>Hope that helps!</p>\n'}, {'answer_id': 155146, 'author': 'Lukáš Rampa', 'author_id': 10560, 'author_profile': 'https://Stackoverflow.com/users/10560', 'pm_score': 3, 'selected': False, 'text': '<p>There is also good library <a href="http://servingxml.sourceforge.net/" rel="noreferrer">ServingXML</a> by Daniel Parker, which is able to convert almost any plain text format to XML and back.</p>\n\n<p>The example for your case can be found <a href="http://servingxml.sourceforge.net/examples/index.html#d62e305" rel="noreferrer">here</a>: It uses heading of field in CSV file as the XML element name.</p>\n'}, {'answer_id': 161058, 'author': 'abarax', 'author_id': 24390, 'author_profile': 'https://Stackoverflow.com/users/24390', 'pm_score': 4, 'selected': False, 'text': '<p>You can do this exceptionally easily using Groovy, and the code is very readable. </p>\n\n<p>Basically, the text variable will be written to <code>contacts.xml</code> for each line in the <code>contactData.csv</code>, and the fields array contains each column.</p>\n\n<pre><code>def file1 = new File(\'c:\\\\temp\\\\ContactData.csv\')\ndef file2 = new File(\'c:\\\\temp\\\\contacts.xml\')\n\ndef reader = new FileReader(file1)\ndef writer = new FileWriter(file2)\n\nreader.transformLine(writer) { line -&gt;\n    fields =  line.split(\',\')\n\n    text = """&lt;CLIENTS&gt;\n    &lt;firstname&gt; ${fields[2]} &lt;/firstname&gt;\n    &lt;surname&gt; ${fields[1]} &lt;/surname&gt;\n    &lt;email&gt; ${fields[9]} &lt;/email&gt;\n    &lt;employeenumber&gt; password &lt;/employeenumber&gt;\n    &lt;title&gt; ${fields[4]} &lt;/title&gt;\n    &lt;phone&gt; ${fields[3]} &lt;/phone&gt;\n    &lt;/CLIENTS&gt;"""\n}\n</code></pre>\n'}, {'answer_id': 208799, 'author': 'Simmo', 'author_id': 25694, 'author_profile': 'https://Stackoverflow.com/users/25694', 'pm_score': 4, 'selected': False, 'text': '<p>You could use <strong>XSLT</strong>.  Google it and you will find a few examples e.g. <a href="http://andrewjwelch.com/code/xslt/csv/csv-to-xml_v2.html" rel="noreferrer">CSV to XML</a>\nIf you use <strong>XSLT</strong> you can then convert the XML to whatever format you want.</p>\n'}, {'answer_id': 3455575, 'author': 'James Selvakumar', 'author_id': 361172, 'author_profile': 'https://Stackoverflow.com/users/361172', 'pm_score': 4, 'selected': False, 'text': '<p>The big difference is that <a href="http://jsefa.sourceforge.net/index.html" rel="noreferrer">JSefa</a> brings in is that it can serialize your java objects to  CSV/XML/etc files and can deserialize back to java objects. And it\'s driven by annotations which gives you lot of control over the output. </p>\n\n<p>JFileHelpers also looks interesting.</p>\n'}, {'answer_id': 23096745, 'author': 'Ibrabel', 'author_id': 3517232, 'author_profile': 'https://Stackoverflow.com/users/3517232', 'pm_score': 2, 'selected': False, 'text': '<p>I had the same problem and needed an application to convert a CSV file to a XML file for one of my projects, but didn\'t find anything free and good enough on the net, so I coded my own Java Swing CSVtoXML application.</p>\n\n<p>It\'s available from my website <a href="https://sites.google.com/site/ibrabel/freewares/csvtoxml" rel="nofollow">HERE</a>. Hope it will help you. </p>\n\n<p>If not, you can easily code your own like I did; The source code is inside the jar file so modify it as you need if it doesn\'t fill your requirement.</p>\n'}, {'answer_id': 29953381, 'author': 'StaxMan', 'author_id': 59501, 'author_profile': 'https://Stackoverflow.com/users/59501', 'pm_score': 2, 'selected': False, 'text': '<p>Jackson processor family has backends for multiple data formats, not just JSON. This includes both XML (<a href="https://github.com/FasterXML/jackson-dataformat-xml" rel="noreferrer">https://github.com/FasterXML/jackson-dataformat-xml</a>) and CSV (<a href="https://github.com/FasterXML/jackson-dataformat-csv/" rel="noreferrer">https://github.com/FasterXML/jackson-dataformat-csv/</a>) backends.</p>\n\n<p>Conversion would rely on reading input with CSV backend, write using XML backend. This is easiest to do if you have (or can define) a POJO for per-row (CSV) entries. This is not a strict requirement, as content from CSV may be read "untyped" as well (a sequence of <code>String</code> arrays), but requires bit more work on XML output.</p>\n\n<p>For XML side, you would need a wrapper root object to contain array or <code>List</code> of objects to serialize.</p>\n'}]
['https://Stackoverflow.com/questions/123', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/78/']