Monday, July 14, 2008

Careful with SAX parser

When parsing xml documents using SAX parser one need to attach an implementation of org.xml.sax.DocumentHandler to receive notifications from the parser. One of the tricky methods in this interface is public void characters(char[] ch, int start, int length) throws org.xml.sax.SAXException. Below is the extract from java docs:

The Parser will call this method to report each chunk of character data. SAX parsers may return all contiguous character data in a single chunk, or they may split it into several chunks; however, all of the characters in any single event must come from the same external entity so that the Locator provides useful information.

The underlined part above is the thing to be handled carefully. One can not simply read the data and allocate to a String as this method might get called repeatedly!! Below is one example of handling this:

// Buffer for holding the element data
StringBuffer dataBuffer = new StringBuffer();
public void characters(char[] ch, int start, int length) throws SAXException
{
dataBuffer.append(ch, start, length);
}

// Get the data from the buffer in endElement method call

One more quirk is that the characters method removes all encoding for special characters like &, <, > etc. So if the xml data contains these special characters outside CDATA section, one need to handle them explicitly !!

No comments:

Post a Comment