Android:无法从xml读取

时间:2014-08-27 06:34:27

标签: java android xml xml-parsing

尝试从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"),但没有用。什么可能是错误,怎么解决?

3 个答案:

答案 0 :(得分:1)

您不能在运行时使用assets/访问File。您应该使用assets/在运行时访问AssetManager,您可以通过getResources().getAssets()获取。{/ p>

有关详细信息,请参阅Android parse XML file from Assets or internal/external storage

从资产中获取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;
}

答案 1 :(得分:0)

请尝试像这样的东西

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

答案 2 :(得分:0)

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

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

的输入

如果您要将其保存为永久更改,getCacheDir()getFilesDirectory()并执行此类操作

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

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

希望它会有所帮助。

问候 Moonzai