Java. Sax parser. How to manually break parsing? [duplicate]

和自甴很熟 提交于 2019-12-08 16:37:27

问题


Tell me please is it possible to break the process of parsing? I.e. exit this loop not reaching the end of document and corresponding event "endDocument" ?


回答1:


Throw an exception in the handler and catch it in the code block where you started parsing:

try {
    ...
    xmlReader.parse();
} catch (SAXException e) {
    if (e.Cause instanceof BreakParsingException) {
        // we have broken the parsing process
        ....
    }
}

And in your DocumentHandler:

public void startElement(String namespaceURI,
                     String localName,
                     String qName,
                     Attributes atts)
              throws SAXException {
    // ...
    throw new SAXException(new BreakParsingException());
}



回答2:


Simple solution would be to use StAX parsing - instead of SAX. While SAX has push parsing - events are sent to the Handler by the Parsers, StAX is pull parsing, events are given to us through XMLEventReader which can be used similar to an iterator. So, it is easier to implement conditional break to break out of the parsing.




回答3:


You have to throw a SAXException. In order to distiguish it from regular errors I would subclass it with my own Exception class



来源:https://stackoverflow.com/questions/2964315/java-sax-parser-how-to-manually-break-parsing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!