Java / Android - 读取,操作和保存XML文件到内部存储

时间:2015-08-19 23:11:12

标签: android xml save dom-manipulation

我正在开发一个Android应用程序,它将使用一个文件系统,其中数据将存储在xml文件中..

我已成功读取相应文件并更改节点(如果在调试器中查看,则值已更改)但未对我本地保存的文件进行更改..

过程: 1.读取/打开本地文件//完成 2.更改DOM NODE //完成 3.保存我本地文件中的更改< - failed

到目前为止,我知道在遵循一些教程和其他代码片段后,我将不得不使用TransformerFactory,但更改仍未保存到我的文件中。

有人能告诉我我做错了吗?

我的代码:

try {
        File path = a.getFilesDir();
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        Document doc = docBuilder.parse(path.getPath() + "/" + FILENAME_PERMISSIONS);

        NodeList myCourses = doc.getElementsByTagName(NODE_COURSE);

        for (int i = 0; i < myCourses.getLength(); i++) {
            Node course = myCourses.item(i);
            Element e = (Element)myCourses.item(i);

            Node myPermission = course.getFirstChild();
            String name = e.getAttribute(ATTR_NAME);

            switch (name){
                case FLAG_CrossCult:
                    myPermission.setTextContent(boolToString(crossCult));
                    break;

                case FLAG_KAIROS:
                    myPermission.setTextContent(boolToString(kairos));

                    break;

                case FLAG_UnfinStory:
                    myPermission.setTextContent(boolToString(unfinStory));

                    break;

                case FLAG_EmpToInf:
                    myPermission.setTextContent(boolToString(empToInf));

                    break;

                case FLAG_YouthKairos:
                    myPermission.setTextContent(boolToString(youthKairos));

                    break;
            }

            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            DOMSource source = new DOMSource(doc);

            StreamResult streamResult = new StreamResult(new File(path.getPath() + "/" + FILENAME_PERMISSIONS));
            transformer.transform(source,streamResult);





        }


    }
    catch (ParserConfigurationException e){

    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }catch(TransformerConfigurationException e){
        e.printStackTrace();
    } catch (TransformerException e) {
        e.printStackTrace();
    }

1 个答案:

答案 0 :(得分:0)

我找到了问题...

“守则”几乎是正确的。需要进行2项更改:

1:需要使用“new File()”

String myPath = path.getPath() + "/" + FILENAME_PERMISSIONS;
Document doc = docBuilder.parse(new File(myPath));

2:我写错了节点

//Node myPermission = course.getFirstChild();
//is now:

NodeList permissionList = e.getElementsByTagName(NODE_PERMISSION);
Node myPermission = permissionList.item(0);

我会在这里留下问题,因为有人需要这样做..