【发布时间】:2010-11-23 15:16:42
【问题描述】:
我用 Sax 解析一个大的 xml 文档,我想在某些条件成立时停止解析该文档?怎么办?
【问题讨论】:
我用 Sax 解析一个大的 xml 文档,我想在某些条件成立时停止解析该文档?怎么办?
【问题讨论】:
我使用布尔变量“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);
}
});
【讨论】:
android.sax.EndTextElementListener。还有article这里是什么?
我不知道除了异常抛出技术outlined by Tom 之外的中止 SAX 解析的机制。另一种方法是改用StAX parser(参见pull vs push)。
【讨论】:
创建 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();
}
...
}
【讨论】: