// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package routing.demo.convert;

import java.io.StringWriter;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

public  class ConvertCSV2XML {
    public static String convert(String line, String rootname, String fieldnames, char delim, char quote) throws XMLStreamException {
        String[] items = Util.parseCSV(line, delim, quote);
        String[] fieldnames2 = fieldnames.split(",");
        XMLOutputFactory xof = XMLOutputFactory.newInstance();
        StringWriter sw = new StringWriter();
        XMLStreamWriter xsw = xof.createXMLStreamWriter(sw);
        xsw.writeStartDocument();
        xsw.writeStartElement(rootname);
        for(int i = 0; i < fieldnames2.length; i++ ) {
            xsw.writeStartElement(fieldnames2[i]);
            xsw.writeCharacters(items[i]);
            xsw.writeEndElement();
        }
        xsw.writeEndElement();
        xsw.writeEndDocument();
        return sw.toString();
    }
}
