如何使用SAX随时停止解析xml文档?

我用Sax解析一个大的xml文档,我想在某些条件建立时停止解析文档? 怎么做?

创建一个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(); } ... } 

除了Tom概述的exception抛出技术之外,我不知道中止SAX解析的机制。 另一种方法是切换到使用StAX解析器 (请参阅pull vs push )。

我使用布尔变量“ 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,supossing有这个.xml

  
Jorgesys
Android
Java

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