سؤال

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.

هل كانت مفيدة؟

المحلول

Not sure but hoping it helps.

Create a class for exception.

public class MySAXTerminatorException extends SAXException {
...
}

I guess there is an overridden method named startElement(...) in SAX parser. Keep a global boolean variable, set it to true when you want to and keep checking this value in very first lines of startElement method.

As every-time control has to come to this method, as soon as that boolean becomes true, execution will be terminated with an exception.

Something like this

if (someConditionOrOther) {
    throw new MySAXTerminatorException();
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top