简体   繁体   中英

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

The application when run currently has two TextViews, two TextEdits, with a save button which saves the password and email to String variables. I have an xml file called users.xml to which I would like to save the email and password when the button is pressed(in addition to saving the email and password to String variables) Any suggestions?

Code:

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>

I first suggest to change your xml file to look like this:

<?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>

The tags <user1> , <user2> , ..., <userN> make no sense. If you need to associate an ID to each user, use <user id = "1"> , <user id = "2"> , ..., <user id = "N"> instead.

Then, remember that files in the asset directory are read-only, so don't put your xml file there; the internal storage is fine. The getDocument() method now looks like this:

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;
    }

When the save button gets clicked, do something like this:

//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);

Note that I've added a new field called xmlFileName :

static final String xmlFileName = "users.xml";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM