// 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.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class ConvertXML2CSV {
    public static String convert(String xml, char delim, char quote) throws ParserConfigurationException, SAXException, IOException {
        StringBuilder sb = new StringBuilder();
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new InputSource(new StringReader(xml)));
        NodeList children = doc.getDocumentElement().getChildNodes();
        for(int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if(child.getNodeType() == Node.ELEMENT_NODE) {
                if(i > 0) sb.append(delim);
                Node inside = child.getFirstChild();
                if(inside.getNodeType() == Node.TEXT_NODE) {
                    String val = inside.getNodeValue();
                    sb.append(Util.formatValue(val, quote, QuoteHandling.DOUBLING));
                } else {
                    throw new RuntimeException("CSV does not support nested structures");
                }
            }
        }
        return sb.toString();
    }
}
