xml解析dom文件

nkcskrwz  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(313)

我正在尝试在内部存储中创建一个简单的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();
    }
}

为确保写入无问题,文件写入正确
当我尝试读取时,出现了一个错误:找不到文件
有人能帮我吗?
谢谢
毛罗

daolsyd0

daolsyd01#

在存储时,您正在存储在内部文件目录中,但在检索时,您只提供名称
例如,它在data/data/[package name]/files/[file\u name]中写入,但您正在尝试从[file\u name]检索。
因此,在读取xml文件时,不必直接从文件名获取,您可以这样尝试,

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

注意:您可以 getFilesDir() 从上下文,所以尝试在参数中发送上下文。

相关问题