[英]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. 该应用程序当前在运行时具有两个TextViews,两个TextEdits,以及一个保存按钮,用于将密码和电子邮件保存到String变量。 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?
我有一个名为users.xml的xml文件,当按下按钮时,我想在其中保存电子邮件和密码(除了将电子邮件和密码保存到String变量之外)有什么建议吗?
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: 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文件更改为如下所示:
<?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. 标签
<user1>
, <user2>
,..., <userN>
没有任何意义。 If you need to associate an ID to each user, use <user id = "1">
, <user id = "2">
, ..., <user id = "N">
instead. 如果需要将ID与每个用户相关联,请改用
<user id = "1">
, <user id = "2">
,..., <user id = "N">
。
Then, remember that files in the asset directory are read-only, so don't put your xml file there; 然后,请记住资产目录中的文件是只读的,因此请不要在其中放置xml文件。 the internal storage is fine.
内部存储很好。 The
getDocument()
method now looks like this: 现在,
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;
}
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
: 请注意,我添加了一个名为
xmlFileName
的新字段:
static final String xmlFileName = "users.xml";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.