Rob Sked
Rob Sked

Reputation: 287

Java: CSV to XML using Jackson

I'm trying to update the following code to output a CSV file into XML. The code below does a brilliant job in converting the CSV to JSON using the headers in the CSV to make the required JSON.

But I want to output as XML instead, and I can't seem to find any good advice to complete this.

Would appreciate some pointers.

package reader;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;

public class JacksonPackage
{

    public static void main(String[] args) throws Exception
    {
        File input = new File("c:\\temp\\data.csv");
        File output = new File("c:\\temp\\data.json");

        List<Map<?, ?>> data = readObjectsFromCsv(input);
        writeAsJson(data, output);
    }

    public static List<Map<?, ?>> readObjectsFromCsv(File file)
            throws IOException
    {
        CsvSchema bootstrap = CsvSchema.emptySchema().withHeader();
        CsvMapper csvMapper = new CsvMapper();
        MappingIterator<Map<?, ?>> mappingIterator = csvMapper
                .reader(Map.class).with(bootstrap).readValues(file);
        return mappingIterator.readAll();
    }

    public static void writeAsJson(List<Map<?, ?>> data, File file)
            throws IOException
    {
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(file, data);
    }

}

Upvotes: 2

Views: 1543

Answers (1)

forty-two
forty-two

Reputation: 12817

Isn't it just a matter of replacing ObjectMapper with XmlMapper?

Upvotes: 2

Related Questions