一 xml文件生产
使用 XmlSerializer 类,编写数据
File file = new File(getFilesDir(), "user.xml");
String name = etUser.getText().toString().trim();
String psw = etPsw.getText().toString().trim();
try {
OutputStream os = new FileOutputStream(file);
XmlSerializer serializer = Xml.newSerializer();
serializer.setOutput(os, "UTF-8"); //设置输出流
serializer.startDocument("UTF-8", true);
serializer.startTag(null, "user");
serializer.startTag(null, "name");
serializer.text(name);
serializer.endTag(null, "name");
serializer.startTag(null, "psw");
serializer.text(psw);
serializer.endTag(null, "psw");
serializer.endTag(null, "user");
serializer.endDocument();
os.close();
Toast.makeText(getApplicationContext(), "success", 0).show();
} catch (Exception e) {
e.printStackTrace();
}
二 解析xml 文件(数据)
使用 XmlPullParser 类解析
try {
File file = new File(getFilesDir(), "user.xml");
XmlPullParser pullParser = Xml.newPullParser();
InputStream is = new FileInputStream(file);
pullParser.setInput(is, "UTF-8");
int evenType = pullParser.getEventType();
while(evenType != pullParser.END_DOCUMENT) {
if(evenType == pullParser.START_TAG){
if(pullParser.getName().equals("name")) {
/*
* <user type="">
* 如果在 TAG 中含有属性
* String type = pullParser.getAttributeValue(index); //获取属性值
* index 代表 第几个属性
*/
tvUser.setText(pullParser.nextText());
} else if(pullParser.getName().equals("psw")) {
tvPsw.setText(pullParser.nextText());
}
}
evenType = pullParser.next();
}
is.close();
Toast.makeText(getApplicationContext(), "PullParser success", 0).show();
} catch (Exception e) {
e.printStackTrace();
}