【发布时间】:2011-02-27 04:53:34
【问题描述】:
请告诉我是否可以打破解析过程? IE。退出此循环未到达文档末尾和相应事件“endDocument”?
【问题讨论】:
请告诉我是否可以打破解析过程? IE。退出此循环未到达文档末尾和相应事件“endDocument”?
【问题讨论】:
简单的解决方案是使用 StAX 解析 - 而不是 SAX。 SAX 具有推送解析 - 事件由解析器发送到处理程序,StAX 是拉解析,事件通过 XMLEventReader 提供给我们,可以类似于迭代器使用。因此,更容易实现条件中断来突破解析。
【讨论】:
在处理程序中抛出异常并在您开始解析的代码块中捕获它:
try {
...
xmlReader.parse();
} catch (SAXException e) {
if (e.Cause instanceof BreakParsingException) {
// we have broken the parsing process
....
}
}
在你的 DocumentHandler 中:
public void startElement(String namespaceURI,
String localName,
String qName,
Attributes atts)
throws SAXException {
// ...
throw new SAXException(new BreakParsingException());
}
【讨论】:
你必须抛出一个 SAXException。为了将它与常规错误区分开来,我将使用我自己的异常类对其进行子类化
【讨论】: