简体   繁体   English

Java-在Android Studio中使用DocumentBuilder / XML解析器

[英]Java - Using DocumentBuilder/XML parser in Android studio

I'm trying to use dom XML parser but it crashes at with IOException 我正在尝试使用dom XML解析器,但是在IOException时崩溃

Document doc = builder.parse(file); 

The code: 编码:

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();
}

I think theres something wrong the the file path. 我认为文件路径有问题。 The fooddata.xml file is in /res/xml/fooddata.xml & /res/raw/fooddata.xml, I've tried access it in different way but nothing works. fooddata.xml文件位于/res/xml/fooddata.xml和/res/raw/fooddata.xml中,我尝试以其他方式访问它,但没有任何效果。

I get IOException from try/catch 我从try / catch得到IOException

How do I get the builder.parse(file) to work? 如何使builder.parse(file)工作?

The fooddata.xml file is in /res/xml/fooddata.xml & /res/raw/fooddata.xml fooddata.xml文件位于/res/xml/fooddata.xml和/res/raw/fooddata.xml中

Those are files on your development machine . 这些是开发计算机上的文件。 They are not files on the Android device. 它们不是 Android设备上的文件。 Resources are merely entries in the APK file on the device. 资源仅仅是设备上APK文件中的条目。

Replace: 更换:

File file = new File(getResources().getResourceName(R.raw.fooddata));
Document doc = builder.parse(file);

with: 有:

Document doc=builder.parse(getResources().openRawResource(R.raw.fooddata));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM