java 如何随时停止使用 SAX 解析 xml 文档?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1345293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to stop parsing xml document with SAX at any time?
提问by Diablo.Wu
I parse a big xml document with Sax, I want to stop parsing the document when some condition establish? How to do?
我用 Sax 解析了一个大的 xml 文档,我想在某些条件成立时停止解析文档?怎么做?
回答by Tom
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).
创建 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();
}
...
}
回答by McDowell
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).
除了Tom 概述的异常抛出技术之外,我不知道有什么机制可以中止 SAX 解析。另一种方法是切换到使用StAX 解析器(参见pull vs push)。
回答by Jorgesys
I use a boolean variable "stopParse" to consume the listeners since i don′t like to use throw new SAXException();
我使用一个布尔变量“ stopParse”来消耗监听器,因为我不喜欢使用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
@PanuHaaramo,假设有这个 .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:
使用 android SAX 获取“title”值的解析器必须是:
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);
}
});

