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

时间:2015-02-07 15:44:45

标签: java android xml xml-parsing android-studio

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

代码:

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>

1 个答案:

答案 0 :(得分:0)

我首先建议将您的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";