【问题标题】:premature end of file while parsing an xml file on android在android上解析xml文件时文件过早结束
【发布时间】:2012-12-30 23:55:18
【问题描述】:

我正在尝试使用 XOM 作为 XML 库从 Android 应用程序读取 xml 文件。我正在尝试这个:

Builder parser = new Builder();
Document doc = parser.build(context.openFileInput(XML_FILE_LOCATION));

但即使文件为空,我也会收到 nu.xom.ParsingException: Premature end of file.

我需要解析一个非常简单的XML 文件,并且我准备使用另一个库而不是 XOM,所以如果有更好的库,请告诉我。或者只是使用 XOM 解决问题。

如果有帮助,我将使用 xerces 来获取解析器。

-----编辑-----

PS:这样做的目的不是解析一个空文件,该文件恰好在第一次运行时显示此错误是空的。

【问题讨论】:

  • XML 文件中的数据是什么?似乎您至少缺少关闭标签</tag>
  • (对不起,我更倾向于关注代码而不是口头描述。)解析一个空文件似乎很愚蠢。也许您应该在尝试解析文件之前检查文件的大小。

标签: java android xml xml-parsing xom


【解决方案1】:

如果您关注this 帖子到最后,这似乎与xerces 以及它是一个空文件的事实有关,并且他们没有在xerces 方面达成解决方案。

所以我处理的问题如下:

Document doc = null;
try {
    Builder parser = new Builder();
    doc = parser.build(context.openFileInput(XML_FILE_LOCATION));
}catch (ParsingException ex) { //other catch blocks are required for other exceptions.
   //fails to open the file with a parsing error.
   //I create a new root element and a new document.
   //I fill them with xml data (else where in the code) and save them.
    Element root = new Element("root");
    doc = new Document(root);       
}

然后我可以用doc 做任何我想做的事。并且您可以添加额外的检查以确保原因确实是一个空文件(例如检查问题中 sam 的 cmets 之一指示的文件大小)。

【讨论】:

  • 与其捕获异常(我相信其他场景也可能抛出ParsingException),我想知道以某种方式检查xml文件是否不是那么难看'空的'。也许您可以检查底层FileChannelsize()FileInputStream 中的available() 字节?
  • Whups,不知道我是怎么忽略的。 :/ 只是想确保您了解一种更“干净”的方法。
  • 是的 .. 抱歉,我没有时间写干净的方法,现在是凌晨 3 点,我不想让这个问题悬而未决。
【解决方案2】:

空文件不是格式良好的 XML 文档。抛出 ParsingException 是正确的做法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-20
    • 2013-04-08
    • 2012-04-28
    • 2017-04-20
    • 1970-01-01
    • 2012-06-25
    • 2012-06-22
    • 1970-01-01
    相关资源
    最近更新 更多