Development

Convert XML to JSON

There are many ways that you could convert XML to JSON, but it isn’t easily a reversible transformation - XML, with namespaces, elements, and attributes models a more nuanced system than JSON, but many things don’t need all that complexity.

This may or may not suit your requirements. It loses lots of information, but maybe good enough for you.

You will need

import nu.xom.Attribute;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Elements;
import nu.xom.Text;
import org.codehaus.jettison.mapped.MappedNamespaceConvention;
import org.codehaus.jettison.mapped.MappedXMLStreamWriter;
 
import javax.xml.stream.XMLStreamException;
import java.io.Writer;
 
public class XmlToJSon {
    private final Document document;
    private MappedXMLStreamWriter streamWriter;
 
    public XmlToJSon(Document document, Writer output) {
        this.document = document;
        this.streamWriter = new MappedXMLStreamWriter(new MappedNamespaceConvention(), output);
    }
 
    public void convert() throws XMLStreamException {
        streamWriter.writeStartDocument();
        convert(document.getRootElement());
        streamWriter.writeEndDocument();
    }
 
    private void convert(Element element) throws XMLStreamException {
        streamWriter.writeStartElement(element.getLocalName());
        for (int i = 0; i < element.getAttributeCount(); i++) {
            convert(element.getAttribute(i));
        }
 
        if (element.getChildCount() == 1 && element.getChild(0) instanceof Text) {
            streamWriter.writeCharacters(element.getValue());
        } else {
            Elements elements = element.getChildElements();
            for (int i = 0; i < elements.size(); i++) {
                convert(elements.get(i));
            }
        }
        streamWriter.writeEndElement();
    }
 
    private void convert(Attribute attribute) throws XMLStreamException {
        streamWriter.writeAttribute(attribute.getLocalName(), attribute.getValue());
    }
}
comments powered by Disqus