我用 Sax 解析一个大的 xml 文档,我想在某些条件成立时停止解析文档?怎么做?
问问题
18276 次
3 回答
39
创建 SAXException 的特化并抛出它(您不必创建自己的特化,但这意味着您可以自己专门捕获它并将其他 SAXExceptions 视为实际错误)。
public class MySAXTerminatorException extends SAXException {
...
}
public void startElement (String namespaceUri, String localName,
String qualifiedName, Attributes attributes)
throws SAXException {
if (someConditionOrOther) {
throw new MySAXTerminatorException();
}
...
}
于 2009-08-28T06:26:37.870 回答
4
除了Tom 概述的异常抛出技术之外,我不知道有一种机制可以中止 SAX 解析。另一种方法是切换到使用StAX 解析器(请参阅pull 与 push)。
于 2009-08-28T09:05:46.507 回答
2
我使用布尔变量“ 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);
}
});
更新:
@PanuHaaramo,假设有这个 .xml
<root>
<article>
<title>Jorgesys</title>
</article>
<article>
<title>Android</title>
</article>
<article>
<title>Java</title>
</article>
</root>
使用 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);
}
});
于 2014-02-21T01:54:10.680 回答