I've implemented my XML
Parser using SAXParser
, but I cannot find how to set it so that the parsing stops right after a certain number of elements.
I tought to declare a int attribute inside my Handler
that counts the results, and if count>N
the method just returns, but this way the xml document is entirely read anyway.
EDIT
With braj's solution I solved the issue:
Inside the Handler
's implementation:
@Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException,MySAXTerminatorException {
if (count > cap)
throw new MySAXTerminatorException();
Then when we call the parser:
try {
sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
xr.setContentHandler((ContentHandler) handler);
xr.parse(new InputSource(new StringReader(xml)));
output.addAll(handler.getParsedData());
return output;
}
catch(MySAXTerminatorException e){
output.addAll(handler.getParsedData());
return output;
}
And this way it interrupts the parsing when you reach your cap.