2

I need to emit a (potentially large) XML document directly to a stream, so I'd like to do it "SAX style" -- in a streaming fashion, where the document is sent over the wire as I go -- as opposed to "DOM style" -- in a batched fashion, where the document is built in memory and then sent over the wire at the end. I'm sure this is easy to do, but I can't find a good tutorial for the life of me. Thanks in advance for your suggestions.

EDIT To be clear, I'm not particular about which XML API to use as long as it emits the document over the wire as it's being built as opposed to building the whole document in memory.

sigpwned
  • 6,957
  • 5
  • 28
  • 48
  • Check out http://stackoverflow.com/questions/4898590/generating-xml-using-sax-and-java – Pace Apr 02 '13 at 02:26

2 Answers2

4

I'd tend to use StAX for generating XML instead of SAX - the API is easier to use. XML is streamed and not held in memory.

Example:

XMLStreamWriter w = XMLOutputFactory.newInstance().createXMLStreamWriter(System.out);
try
{
    w.writeStartDocument();
    w.writeStartElement("root");
    for (int i = 0; i < 1000; i++)
    {
        w.writeStartElement("number");
        w.writeCharacters(String.valueOf(i));
        w.writeEndElement(); //number
    }
    w.writeEndElement(); //root
    w.writeEndDocument();
}
finally
{
    w.close();
}
prunge
  • 22,460
  • 3
  • 73
  • 80
0

You're best approach may depend on where your data originates. Does it start out in memory? Are you retrieving data from an external source like a service or database?

If you're converting a large list of objects, like a query from a database, then an object serializer (like Jackson, for example) that does simple object to XML conversion might still fit your goal of low memory consumption-- you just apply it iteratively. Open your stream, read a row, serialize it, output it to the stream, read the next row, serialize it, etc. You keep the same output stream open the whole time, but the amount of XML code living in memory is always kept small.

phatfingers
  • 9,770
  • 3
  • 30
  • 44