How to stop parsing xml document with SAX at any time?
Create a specialization of a SAXException and throw it (you don't have to create your own specialization but it means you can specifically catch it yourself and treat other SAXExceptions as actual errors).
public class MySAXTerminatorException extends SAXException {
...
}
public void startElement (String namespaceUri, String localName,
String qualifiedName, Attributes attributes)
throws SAXException {
if (someConditionOrOther) {
throw new MySAXTerminatorException();
}
...
}
Java. Sax parser. How to manually break parsing?
Throw an exception in the handler and catch it in the code block where you started parsing:
try {
...
xmlReader.parse();
} catch (SAXException e) {
if (e.Cause instanceof BreakParsingException) {
// we have broken the parsing process
....
}
}
And in your DocumentHandler:
public void startElement(String namespaceURI,
String localName,
String qName,
Attributes atts)
throws SAXException {
// ...
throw new SAXException(new BreakParsingException());
}
How do I stop parsing an XML document with IVBSAXXMLReader in Delphi?
Simply calling Abort;
is fine. In this case, just override SafeCallException
in your IVBSAXContentHandler
implementor class:
function TContentHandler.SafeCallException(ExceptObject: TObject; ExceptAddr: Pointer): HRESULT;
begin
Result := HandleSafeCallException(ExceptObject, ExceptAddr, TGUID.Empty, '', '');
end;
HandleSafeCallException
supplied in ComObj
will cause EAbort
you're raising to be translated into a HRESULT
value E_ABORT
which will then be translated back to EAbort
by SafeCallError
.
Alternatively, you can raise your own exception class, override SafeCallException
to translate it into your specific HRESULT
value and replace SafeCallErrorProc
with your own to translate it back into your Delphi exception which you can then handle on the calling side.
Java Sax Parser - stop processing in EndElementListener
Define a new unchecked exception called "SaxBreakOutException":
class SaxBreakOutException extends RuntimeException {
}
Throw this in your listener:
chanItem.setEndElementListener(new EndElementListener() {
public void end() {
_items.add(_item);
if (++_currentItem == _maxElements) {
throw new SaxBreakOutException();
}
}
});
And catch it in the code that calls XmLReader.parse():
reader.setContentHandler(handler);
try {
reader.parse(new InputSource(new StringReader(xml)));
} catch (SaxBreakOutException allDone) {
}
Alternatively, switch to Android's XmlPullParser which doesn't require exceptions to break out early.
Can I somehow tell to SAX parser to stop at some element and get its child nodes as a string?
It does not seem to be offered by the xml.sax
API, but you can utilize another way of interrupting control flow: exceptions.
Just define a custom exception for that purpose:
class FinishedParsing(Exception):
pass
Raise this exception in your handler when you have finished parsing and simply ignore it.
try:
parser.parse(xml)
except FinishedParsing:
pass
End parsing xml early in sax
The below code should work for you.
The idea is to raise a specific exception, to catch it and ignore it ..
class HaveEnoughRows(Exception):
pass
class myHandler(sax.ContentHandler):
def __init__(self):
super().__init__()
self.count = 0
def startElement(self, name, attrs):
if name == 'row':
self.count += 1
def endElement(self, name):
if self.count > 10000:
# stop the parser
raise HaveEnoughRows()
def sax_parse():
parser = sax.make_parser()
parser.setFeature(sax.handler.feature_namespaces, 0)
handler = myHandler()
parser.setContentHandler(handler)
try:
parser.parse("url")
except HaveEnoughRows:
pass
print('hello')
Is there a way to Stop or Quit parsing from within a DefaultHandler?
you can throw the SAXException
to stop parsing
you can use a subclass of it to ensure the parsing failed because of your decision and not a random parse exception
Related Topics
Dynamic Generic Typing in Java
How to Apply Multiple Predicates to a Java.Util.Stream
How Does System.Out.Print() Work
How to Pass a Value from One Jsp to Another Jsp Page
Pros and Cons of Package Private Classes in Java
Why Do Constructors in Java Not Have a Return Type
How to Save User Settings in Java Application
Jackson Dynamic Property Names
File Upload Using Selenium Webdriver and Java Robot Class
Mockito: Mock Private Field Initialization
Java: Set Timeout on a Certain Block of Code
How to Stop the Task Scheduled in Java.Util.Timer Class
How to Disable Loggers of a Class or of Whole Package
Extended Server_Name (Sni Extension) Not Sent with Jdk1.8.0 But Send with Jdk1.7.0
How to Set Color to a Certain Row If Certain Conditions Are Met Using Java