How to stop parsing xml document with SAX at any time?
I parse a big xml document with Sax, I want to stop parsing the document when some condition establish? How to do?
创建SAXException的专门化并抛出它(您不必创建自己的专业化,但它意味着您可以自己专门捕获它并将其他SAXException作为实际错误处理)。
public class MySAXTerminatorException extends SAXException {
...
}
public void startElement (String namespaceUri, String localName,
String qualifiedName, Attributes attributes)
throws SAXException {
if (someConditionOrOther) {
throw new MySAXTerminatorException();
}
...
}
I am not aware of a mechanism to abort SAX parsing other than the exception throwing technique outlined by Tom. An alternative is to switch to using the StAX parser (see pull vs push).
I use a boolean variable " stopParse
" to consume the listeners since i don´t like to use throw new SAXException()
;
private boolean stopParse;
article.getChild("title").setEndTextElementListener(new EndTextElementListener(){
public void end(String body) {
if(stopParse) {
return; //if stopParse is true consume the listener.
}
setTitle(body);
}
});
Update:
@PanuHaaramo, supossing to have this .xml
<root>
<article>
<title>Jorgesys</title>
</article>
<article>
<title>Android</title>
</article>
<article>
<title>Java</title>
</article>
</root>
the parser to get the "title" value using android SAX must be:
import android.sax.Element;
import android.sax.EndTextElementListener;
import android.sax.RootElement;
...
...
...
RootElement root = new RootElement("root");
Element article= root.getChild("article");
article.getChild("title").setEndTextElementListener(new EndTextElementListener(){
public void end(String body) {
if(stopParse) {
return; //if stopParse is true consume the listener.
}
setTitle(body);
}
});
链接地址: http://www.djcxy.com/p/91084.html