Android DOM 解析太慢
我正在尝试使用 DOM 解析器解析 Web 响应,如下所示:
public static Document parseDocument(InputStream sr) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setIgnoringComments(true);
dbf.setIgnoringElementContentWhitespace(true);
dbf.setCoalescing(true);
//dbf.setValidating(false);
Document xdoc = dbf.newDocumentBuilder().parse(new InputSource(sr));
xdoc.normalize();
return xdoc;
}
问题是
Document xdoc = dbf.newDocumentBuilder().parse(new InputSource(sr));
需要 3 分钟才能执行。我的 xml 文件有 3800 行。 是不是很正常,如何改进?
谢谢。
I am trying to parse an web response with DOM parser like this:
public static Document parseDocument(InputStream sr) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setIgnoringComments(true);
dbf.setIgnoringElementContentWhitespace(true);
dbf.setCoalescing(true);
//dbf.setValidating(false);
Document xdoc = dbf.newDocumentBuilder().parse(new InputSource(sr));
xdoc.normalize();
return xdoc;
}
The problem is that
Document xdoc = dbf.newDocumentBuilder().parse(new InputSource(sr));
takes 3 min to be executed. My xml file has 3800 lines.
Is than normaé and how to improve this?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这对于 Android 中的 DOM 解析来说太大了。内存消耗和对象分配是不利的。 SAX asin 之前的答案是可行的解决方案,但是 Pull-Parser (也包含在 android API 中)是更好、更现代的选择,因为它更容易编程
(使用 SAX 解析器驱动处理并将 XML 事件推送到您的处理程序,而 XPP 是您的应用程序驱动解析器并将 xml 事件从流中拉出)
更好的选择是构建在拉解析器之上的一些轻量级数据绑定框架 - jackson、xstream等等。他们只会提供对象 - 你根本不必担心 xml 解析
This is too big for DOM parsing in android. Memory consumption and object allocation is porhobitive. SAX asin previous answer is workable solution, but Pull-Parser ( also contained in android APIs ) is better and more modern choice, as it is easier to program
( with SAX parser drives procesing and pushes XML events ti your handler, while XPP it is your application driving parser and pulling xml events out of stream )
Even better choice would be some lightweight data binding framework built on top of pull parser - jackson, xstream etc. They will deliver just objects - s you do not have to worry about xml parsing at all