How to implement a correct sax xml parser
Hi folks,
I had been working with xml recently and case across the SAX parser. According to the java doc the “characters” method of the handler may send you discontinues chunks of data. For most of the time this doesn’t happen. But it happens. It happened to me. Depending on the contents of you xml document. So I have implemented a SAX parser with an internal buffer which caches all the incoming data to the characters method and process the whole chunk of data in the endElement method. This method ensures correct behavior of SAX parser. So here’s an example.
public abstract class SampleSAXParser extends HandlerBase {
private StringBuilder recievedData;
public EspmlCardProfileBatchloadHandler(Tracer pTracer,
ReportManager pReportMgr, EspmlElementFieldsValidator validator) {
recievedData = new StringBuilder();// initializing the buffer for input
}
// catch exceptions
@Override
public void startElement(String uri, String name, String qName,
Attributes attrs) throws SAXException {
}
// catch exceptions
/* to do implement BadParameterFormatExceptionRca exceptions */
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
String value = String.valueOf(ch, start, length).trim();
recievedData.append(value); //append input data to buffer
}
private void handleBufferedData() throws Exception {
if (recievedData.length() > 0) {
String value = recievedData.toString();
processRecievedData(value); //process data
recievedData = new StringBuilder(); //create an empty buffer for next read
}
}
// catch exceptions
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
handleBufferedData(); //process element contents
}
}
Hope this helps. Thank you.
Regards,
Lasith.