Generating XML using SAX and Java

Lunchbox picture Lunchbox · Feb 4, 2011 · Viewed 60.6k times · Source

Anyone know of a good tutorial (or have a good example) for writing XML using the SAX framework (or something similar) and Java? Searching has yielded very little in terms of useful results. I'm trying to export from an Android app and am looking to avoid as much memory overhead as possible.

Answer

morja picture morja · Feb 4, 2011

SAX parsing is for reading documents, not writing them.

You can write XML with the XMLStreamWriter:

OutputStream outputStream = new FileOutputStream(new File("doc.xml"));

XMLStreamWriter out = XMLOutputFactory.newInstance().createXMLStreamWriter(
                new OutputStreamWriter(outputStream, "utf-8"));

out.writeStartDocument();
out.writeStartElement("doc");

out.writeStartElement("title");
out.writeCharacters("Document Title");
out.writeEndElement();

out.writeEndElement();
out.writeEndDocument();

out.close();