Android xml文件的序列化

Android提供瞭XmlSerializer來實現XML文件的序列化。相比傳統方式,更高效安全。

傳統方式:

public void backSms(View view){
		//假設我已經獲取到瞭所有的短信
		StringBuilder sb = new StringBuilder();
		sb.append("");
		sb.append("");
		for(SmsInfo info:smsInfos){
			sb.append("");
			
			sb.append("");
			sb.append(info.getAddress());
			sb.append("");
		
			
			sb.append("");
			sb.append(info.getType());
			sb.append("");
			
			sb.append("");
			sb.append(info.getBody());
			sb.append("");
			
			sb.append("");
			sb.append(info.getBody());
			sb.append("");
			
			sb.append("");
		}
		sb.append("");
		try{
			File file = new File(Environment.getExternalStorageDirectory(),"backup.xml");
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(sb.toString().getBytes());
			Toast.makeText(this, "備份成功", Toast.LENGTH_LONG).show();
		}catch(Exception e){
			e.printStackTrace();
			Toast.makeText(this, "備份失敗", Toast.LENGTH_LONG).show();
		}
		
	}

采用XmlSerializer實現的方式:

public void backSms2(View view){
		try{
			XmlSerializer serializer =  Xml.newSerializer();
			File file = new File(Environment.getExternalStorageDirectory(),"backup2.xml");
			FileOutputStream os = new FileOutputStream(file);
			//初始化序列號器 指定XML數據寫入到哪個文件 並且指定文件的編碼方式
			serializer.setOutput(os,"utf-8");
			serializer.startDocument("uft-8", true);
			serializer.startTag(null, "smss");
			for(SmsInfo info:smsInfos){
				serializer.startTag(null, "sms");
				serializer.attribute(null, "id", info.getId()+"");
				
				serializer.startTag(null, "body");
				serializer.text(info.getBody());
				serializer.endTag(null, "body");
				
				serializer.startTag(null, "address");
				serializer.text(info.getAddress());
				serializer.endTag(null, "address");
				
				serializer.endTag(null, "sms");
			}
			
			serializer.endTag(null, "smss");
			serializer.endDocument();
		}catch(Exception e){
			e.printStackTrace();
			Toast.makeText(this, "備份失敗", 0);
		}
		
	}

發佈留言