How to stop parsing xml document with SAX at any time?

被刻印的时光 ゝ 提交于 2019-11-26 06:45:56

问题


I parse a big xml document with Sax, I want to stop parsing the document when some condition establish? How to do?


回答1:


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).

public class MySAXTerminatorException extends SAXException {
    ...
}

public void startElement (String namespaceUri, String localName,
                           String qualifiedName, Attributes attributes)
                        throws SAXException {
    if (someConditionOrOther) {
        throw new MySAXTerminatorException();
    }
    ...
}



回答2:


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).




回答3:


I use a boolean variable "stopParse" to consume the listeners since i don´t like to use 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

<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:

   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);
                }
            });


来源:https://stackoverflow.com/questions/1345293/how-to-stop-parsing-xml-document-with-sax-at-any-time

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