繁体   English   中英

Android:无法从xml读取

[英]Android:Unable to read from xml

尝试从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从资产或内部/外部存储中解析XML文件

从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;
}

请尝试这样的事情

AssetManager assetManager = getBaseContext().getAssets();

 try{
   InputStream is = assetManager.open("data.xml");
   SAXParserFactory spf = SAXParserFactory.newInstance();
   SAXParser sp = spf.newSAXParser();
   XMLReader xr = sp.getXMLReader();

   OrderXMLHandler myXMLHandler = new OrderXMLHandler();
   xr.setContentHandler(myXMLHandler);
   InputSource inStream = new InputSource(is);
   xr.parse(inStream);

   String dataField1 = myXMLHandler.getDataField1(); //Use your fields in the data.xml file
   String dataField2 = myXMLHandler.getDataField2(); //Use your fields in the data.xml file
 is.close();

 } catch (Exception e) {
    e.printStackTrace(); 
 }

只需将文件复制到应用程序的内部缓存中,就像这样

  InputStream xmlIS = getAssets.open("data/data.xml");

  File xmlFile = new File(getCacheDir(), "data.xml");
  FileOutputStream xmlStream = new FileOutputStream(xmlFile);

  byte[] buffer = new byte[1024];
  int read = -1;
  while((read = xmlIs.read(buffer)) > 0) {
        xmlStream.write(buffer, 0, read);
        xmlStream.flush();
  }

现在,您可以将xmlFile设置为dBuilder.parse(xmlFile);输入dBuilder.parse(xmlFile);

如果要永久保存它,请将getCacheDir()更改为getFilesDirectory()并执行类似的操作

  File xmlFile = new File(getFilesDirectory(), "data.xml");
  if(!xmlFile.exists()) {
  ... // the code which is above
  }

然后将xmlFile传递给dbBuilder.parse函数。

希望会有所帮助。

问候Moonzai

暂无
暂无

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

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