中止 SAX 解析中间文档?
我正在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能需要查看 XMLPullParser 作为只需不调用 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.