SAX based approach to build/create XML documents

If you dont want to build a xml document using StringBuffer or DOM then you can look at doing it with SAX. A  sample code that does this and passes the document to a byte array stream is as follows

SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
TransformerHandler handler=factory.newTransformerHandler();
Transformer transformer = handler.getTransformer();

//set the stream
ByteArrayOutputStream bos = new ByteArrayOutputStream();
StreamResult streamResult = new StreamResult(bos);

String data = null;
AttributesImpl attr = new AttributesImpl();
handler.startElement(“”, “”, “Root”, null);
handler.startElement(“”, “”, “XXX”, null);
handler.startElement(“”, “”, “YYY”, null);
handler.characters(“Test Data”.toCharArray(), 0, 9);
handler.endElement(“”, “”, “YYY”);
handler.endElement(“”, “”, “XXX”);
handler.endElement(“”, “”, “Root”);
byte[] bytes= bos.toByteArray();

Using null in the startDocument and startElement methods for the namespace and localName params caused NullPointerException at org.apache.xalan.transformer.SerializerSwitcher.switchSerializerIfHTML( Thats the reason why empty strings have been used. I have not tested the code with other SAX parsers.

This entry was posted in Technology and tagged , . Bookmark the permalink.

1 Response to SAX based approach to build/create XML documents

  1. anon says:

    You may want to look at vtd-xml as the state of the art in XML processing, consuming far less memory than DOM


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s