如何通过 java /Android Studio 将节点和值保存到 xml 文件

How to save nodes and values to an xml file through java /Android Studio

运行 时的应用程序当前有两个 TextView,两个 TextEdit,带有一个保存按钮,用于将密码和电子邮件保存到 String 变量。我有一个名为 users.xml 的 xml 文件,我想在按下按钮时将电子邮件和密码保存到其中(除了将电子邮件和密码保存到字符串变量之外) 有什么建议么?

代码:

package com.example.ashwinpraveen1.domdoc;

import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;


public class MainActivity extends ActionBarActivity {

    TextView printText;
    EditText emailEdit, passwordEdit;
    Button saveButton;
    String email,password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final EditText emailEdit = (EditText) findViewById(R.id.emailEdit);
        final EditText passwordEdit = (EditText) findViewById(R.id.passwordEdit);
        Button saveButton = (Button) findViewById(R.id.saveButton);

        Document xmlDoc = getDocument();
        final TextView printText = (TextView) findViewById(R.id.printText);
        // checking if I can retrieve the root node
        printText.setText(xmlDoc.getDocumentElement().getNodeName());


        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                email = emailEdit.getText().toString();
                password = passwordEdit.getText().toString();
                if (email.isEmpty() || password.isEmpty()) {
                    //code when the user presses the "save" button for no reason
                }
            }
        });




            }

            private  Document getDocument() {
                try {
                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    factory.setIgnoringComments(true);
                    factory.setIgnoringElementContentWhitespace(true);
                    //factory.setValidating(true);

                    DocumentBuilder builder = factory.newDocumentBuilder();
                    AssetManager assetManager = this.getAssets();
                    InputStream is = assetManager.open("users.xml");

                    InputSource inStream = new InputSource(is);
                    return builder.parse(inStream);

                }
                catch(Exception e) {
                    TextView printText = (TextView) findViewById(R.id.printText);
                    printText.setText(e.getMessage());
                    return null;
                }
            }



    }

users.xml:

<?xml version="1.0" encoding="UTF-8"?>

<list>
    <users>
        <user1>Bob</user1>
        <pass1>BobNeedsHelpWithxml</pass1>
    </users>
    <users>
        <user2>Ash</user2>
        <pass2>AshNeedsHelpToo</pass2>
    </users>
</list>

我首先建议将您的 xml 文件更改为如下所示:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<users>
    <user>
        <username>Bob</username>
        <password>BobNeedsHelpWithxml</password>
    </user>
    <user>
        <username>Ash</username>
        <password>AshNeedsHelpToo</password>
    </user>
</users>

标签 <user1><user2>、...、<userN> 没有意义。如果您需要为每个用户关联一个 ID,请改用 <user id = "1"><user id = "2">、...、<user id = "N">

然后,请记住资产目录中的文件是只读的,所以不要将 xml 文件放在那里;内部存储很好。 getDocument() 方法现在看起来像这样:

private Document getDocument() {
        Document d = null;
        try {
           FileInputStream  f = openFileInput(xmlFileName);

           DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
           DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
           d = dBuilder.parse(f);
        } catch (ParserConfigurationException | IOException | SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 

        return  d;
    }

单击保存按钮后,执行如下操作:

//append new user
Element users = xmlDoc.getDocumentElement();

Element newUser = xmlDoc.createElement("user");

Element newUsername = xmlDoc.createElement("username");
Element newPassword = xmlDoc.createElement("password");

newUsername.appendChild(xmlDoc.createTextNode(email));
newPassword.appendChild(xmlDoc.createTextNode(password));

newUser.appendChild(newUsername);
newUser.appendChild(newPassword);

users.appendChild(newUser);

//save to file
DOMSource source = new DOMSource(xmlDoc);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
StreamResult result = new StreamResult(openFileOutput(xmlFileName, Context.MODE_PRIVATE)); 
transformer.transform(source, result);

请注意,我添加了一个名为 xmlFileName 的新字段:

static final String xmlFileName = "users.xml";