在尝试从 xml 读取时,我收到 IOException
。
下面是代码
File xmlFile = new File("\\assets\\data\\data.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
dBuilder.parse(xmlFile)
抛出 IOException
。
我也尝试过 new File("/assets/data/data.xml")
和 new File("assets/data/data.xml")
但没有用。可能的错误是什么以及如何解决?
最佳答案
您不能在运行时使用File
访问assets/
。您应该在运行时使用 AssetManager
访问 assets/
,您可以通过 getResources().getAssets()
获取它。
有关更多信息,请参阅 Android parse XML file from Assets or internal/external storage
从 Assets 中获取 xml 为
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(getXml(context,"data/data.xml")));
Document doc = builder.parse(is);
函数是
private String getXml(Context mContext,String path){
String xmlString = null;
AssetManager am = mContext.getAssets();
try {
InputStream is = am.open(path);
int length = is.available();
byte[] data = new byte[length];
is.read(data);
xmlString = new String(data);
} catch (IOException e1) {
e1.printStackTrace();
}
return xmlString;
}
关于java - Android:无法读取xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25520370/