private void backupData() { try { bulidData(); String ENCODING = "utf-8"; XmlSerializer serializer = Xml.newSerializer(); File file = new File(this.getExternalFilesDir(null), "back.xml"); FileOutputStream fos = new FileOutputStream(file); serializer.setOutput(fos, ENCODING); serializer.startDocument(ENCODING, true); serializer.startTag(null, "smses"); for (SmsInfo sms : smsInfos) { serializer.startTag(null, "sms"); serializer.attribute(null, "Content", sms.getContent()); serializer.attribute(null, "Type", String.valueOf(sms.getType())); serializer.endTag(null, "sms"); } serializer.endTag(null, "smses"); serializer.endDocument(); fos.close(); Toast.makeText(this, "備份成功", Toast.LENGTH_SHORT).show(); } catch (Exception e) { e.printStackTrace(); //Toast.makeText(this, e.getMessage(), 0).show(); } }
二、讀取
java
package com.pas.readxml.service; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.os.Environment; import android.util.Xml; public class WeatherService { public static List<String> getWeatherStrings() { try { File SD_path=new File(Environment.getExternalStorageDirectory(),"city.xml"); FileInputStream is=new FileInputStream(SD_path); XmlPullParser parser=Xml.newPullParser(); parser.setInput(is, "utf-8"); int type=parser.getEventType(); /* * 文檔開頭START_DOCUMENT * 文檔結尾END_DOCUMENT */ List<String> city=null; while(type!=XmlPullParser.END_DOCUMENT) { switch (type) { case XmlPullParser.START_TAG: if("ArrayOfString".equals(parser.getName())) { city=new ArrayList<String>(); } else if("string".equals(parser.getName())) { city.add(parser.nextText()); } break; default: break; } type=parser.next(); } return city; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }