2017-07-14 134 views
0

我試圖做一個簡單的DOM作者與讀者在內部存儲解析XML DOM文件

這是代碼

protected void write_xml_file(String file_name) { 
    //if (file_name == null) file_name = "spells.xml"; 
    FileOutputStream fos; 
    try { 
     fos = openFileOutput(file_name, Context.MODE_APPEND); 
     XmlSerializer serializer = Xml.newSerializer(); 
     serializer.setOutput(fos, "UTF-8"); 
     serializer.startDocument(null, Boolean.valueOf(true)); 
     serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); 
     serializer.startTag(null, "spells"); 
     for (int j = 0; j < 3; j++) { 
      serializer.startTag(null, "spell"); 
      serializer.text("a" + j); 
      serializer.endTag(null, "spell"); 
     } 
     serializer.endDocument(); 
     serializer.flush(); 
     fos.close(); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 


} 

protected void read_xml_file(String file_name) { 
    try { 
     File fXmlFile = new File(file_name); 
     DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder dBuilder = null; 
     dBuilder = dbFactory.newDocumentBuilder(); 
     Document doc = dBuilder.parse(fXmlFile); 
     doc.getDocumentElement().normalize(); 
     NodeList nList = doc.getElementsByTagName("spells"); 


     for (int temp = 0; temp < nList.getLength(); temp++) { 

      Node nNode = nList.item(temp); 

      //System.out.println("\nCurrent Element :" + nNode.getNodeName()); 

      if (nNode.getNodeType() == Node.ELEMENT_NODE) { 

       Element eElement = (Element) nNode; 

       //System.out.println("spell id : " + eElement.getAttribute("id")); 
       //System.out.println("name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent()); 
       //System.out.println("description : " + eElement.getElementsByTagName("firstname").item(0).getTextContent()); 
       //System.out.println("school : " + eElement.getElementsByTagName("lastname").item(0).getTextContent()); 

      } 
     } 


     } catch (ParserConfigurationException e) { 
     e.printStackTrace(); 
    } catch (SAXException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

爲寫沒問題,該文件被正確地寫道:

當我嘗試閱讀我有一個錯誤:未找到文件

有人可以幫助我嗎?

感謝

莫羅

回答

0

儲存時,您將可以存儲在內部文件目錄,擷取你只是給剛名

爲例,其在數據寫入/數據/ [包名稱] /文件/ [文件名] ,但您嘗試從[文件名]檢索。的

因此,而不是直接從文件名獲得,而讀取XML文件,你可以嘗試這樣的,

File fXmlFile = new File(context.getFilesDir() + File.separator + file_name); 

Note: you can get getFilesDir() from Context, so try to send context in parameter.