Java-在Android studio中使用DocumentBuilder/XML解析器
我试图使用dom XML解析器,但它在IOException中崩溃Java-在Android studio中使用DocumentBuilder/XML解析器,java,android,xml,parsing,dom,Java,Android,Xml,Parsing,Dom,我试图使用dom XML解析器,但它在IOException中崩溃 Document doc = builder.parse(file); 守则: try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); File file = new File(getResour
Document doc = builder.parse(file);
守则:
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
File file = new File(getResources().getResourceName(R.raw.fooddata));
Document doc = builder.parse(file);
}catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
我想文件路径有问题。
fooddata.xml文件位于/res/xml/fooddata.xml&/res/raw/fooddata.xml中,我尝试过以不同的方式访问它,但没有任何效果
我从try/catch获得IOException
如何让builder.parse(文件)工作
fooddata.xml文件位于/res/xml/fooddata.xml&/res/raw/fooddata.xml中
这些是开发机器上的文件。它们不是安卓设备上的文件。资源只是设备上APK文件中的条目
替换:
File file = new File(getResources().getResourceName(R.raw.fooddata));
Document doc = builder.parse(file);
与:
它似乎工作得更好,但现在我得到了一个OutOfMemoryError。xml文件是30mb。@SimonAnderson这就是DOM的问题:它占用大量内存。您可能必须改用SAX或StAX。@Andreas那么问题是android设备上的ram?因为我的模拟器可以工作fine@SimonAndersson这是我的猜测,是的。@SimonAndersson:如果你打算将XML文件中的所有数据一次性读入内存(DOM),那你就完了。您的应用程序可能没有30MB的堆空间。如果您只需要XML的一个子集,那么就从资源中去掉额外的内容,因为打包这些额外的数据和浪费用户设备上的空间是没有意义的。
Document doc=builder.parse(getResources().openRawResource(R.raw.fooddata));