// 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 ConvertXML2JSON {
    private static void convert(Node node, StringBuilder sb) {
        sb.append("{ ");
        NodeList children = node.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(", ");
                String nam = child.getNodeName();
                Node inside = child.getFirstChild();
                if(inside.getNodeType() == Node.TEXT_NODE) {
                    String val = inside.getNodeValue();
                    sb.append('"');
                    sb.append(nam);
                    sb.append('"');
                    sb.append(": ");
                    sb.append(Util.formatValue(val, '"', QuoteHandling.ESCAPING));
                }
                if(inside.getNodeType() == Node.ELEMENT_NODE) {
                    sb.append('"');
                    sb.append(nam);
                    sb.append('"');
                    sb.append(": ");
                    convert(child, sb);
                }
            }
        }
        sb.append(" }");
    }
    public static String convert(String xml) 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)));
        convert(doc.getDocumentElement(), sb);
        return sb.toString();
    }
}
