【问题标题】:How to stop parsing xml document with SAX at any time?如何随时停止使用 SAX 解析 xml 文档?
【发布时间】:2010-11-23 15:16:42
【问题描述】:

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

【问题讨论】:

    标签: java xml sax


    【解决方案1】:

    我使用布尔变量“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这里是什么?
    • 谢谢。我不是为 Android 开发,但清除它!我想这在常规 Java(我正在使用)中是不可行的。
    【解决方案2】:

    我不知道除了异常抛出技术outlined by Tom 之外的中止 SAX 解析的机制。另一种方法是改用StAX parser(参见pull vs push)。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • 还有其他方法吗?不使用异常。
      • 你为什么不想呢?这就是例外的设计目的。
      • fwiw,这不是异常的设计目的。像这样终止解析不是错误情况。然而,这是做到这一点的唯一方法:-(
      • 事实上,它应该是SAXParseException,这样您就可以填充一个定位器,并在ErrorHandler 上获得回调(这是“整理”的正确位置)。
      • 这是一个很好的例子 - Stop a SAX parser when you have enough data
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-23
      • 1970-01-01
      • 1970-01-01
      • 2011-06-17
      • 2011-04-13
      • 2012-08-27
      相关资源
      最近更新 更多