中止 SAX 解析中间文档?

发布于 2024-08-27 22:47:24 字数 770 浏览 5 评论 0原文

我正在 Android 中使用 SAX 解析器解析一个非常简单的 XML 模式。

示例文件是

<Lists>
<List name="foo">
<Note title="note 1" .../>
<Note title="note 2" .../>
</List>
<List name="bar">
<Note title="note 3" .../>
</List>
</Lists>

... 表示更多注释数据作为不重要的属性。

我使用 SAX 解析器来解析文档,并且仅实现 HandlerBase 的 startElement 和 'endElement' 方法来处理 Note 和 List 节点。

但是,在某些情况下,文件可能非常大并且需要一些时间来处理。我希望能够随时中止解析过程(即用户按下取消按钮)。

我想出的最好方法是在满足某些条件时从 startElement 方法抛出异常(即 boolean stopParsing 为 true)。

是否有有更好的方法吗?

我一直使用 DOM 风格的解析器,所以我不完全理解 SAX 解析器。

最后一点,我在 Android 上运行它,因此我将在工作线程上运行解析器以保持 UI 响应。如果您知道如何在解析器运行时安全地终止线程,那也可以回答我的问题。

I'm parsing a very simple XML schema with a SAX parser in Android.

An example file would be

<Lists>
<List name="foo">
<Note title="note 1" .../>
<Note title="note 2" .../>
</List>
<List name="bar">
<Note title="note 3" .../>
</List>
</Lists>

The ... represents more note data as attributes that aren't important to question.

I use a SAX parser to parse the document and only implement the startElement and 'endElement' methods of the HandlerBase to handle Note and List nodes.

However, In some cases the files can be very large and take some time to process. I'd like to be able to abort the parsing process at any time (i.e. user presses cancel button).

The best way I've come up with is to throw an exception from my startElement method when certain conditions are met (i.e. boolean stopParsing is true).

Is there a better way to do this?

I've always used DOM style parsers, so I don't fully understand the SAX parser.

One final note, I'm running this on Android, so I will have the Parser running on a worker thread to keep the UI responsive. If you know how I can kill the thread safely while the parser is running that would answer my question as well.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心安伴我暖 2024-09-03 22:47:24

您可能需要查看 XMLPullParser 作为只需不调用 next 方法即可轻松执行此操作。您可以更好地控制解析。

XmlPullParser xpp=getResources().getXml(R.xml.lists);
while (xpp.getEventType()!=XmlPullParser.END_DOCUMENT) {
    if (xpp.getEventType()==XmlPullParser.START_TAG) {
        if (xpp.getName().equals("list")) {
            items.add(xpp.getAttributeValue(0));
        }
    }

    xpp.next();
}

You might want to look into XMLPullParser as this could be performed easily by just not calling the next method. You are in more control over the parsing.

XmlPullParser xpp=getResources().getXml(R.xml.lists);
while (xpp.getEventType()!=XmlPullParser.END_DOCUMENT) {
    if (xpp.getEventType()==XmlPullParser.START_TAG) {
        if (xpp.getName().equals("list")) {
            items.add(xpp.getAttributeValue(0));
        }
    }

    xpp.next();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文