我正在尝试使用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:这样做的目的不是解析一个空文件,第一次运行时该文件恰好是空的,显示了这个错误。
答案 0 :(得分:2)
如果您按照this发布到最后,似乎这与xerces
以及它是一个空文件的事实有关,而且他们没有在{{1}上找到解决方案一边。
所以我按如下方式解决了这个问题:
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);
}
做任何我想做的事情。并且您可以添加额外的检查以确保原因确实是一个空文件(例如检查sam对该问题的评论之一所指示的文件大小)。
答案 1 :(得分:1)
空文件不是格式良好的XML文档。抛出ParsingException是正确的做法。