在《Android 生成xml文件》一文中使用流的形式写入xml格式文件,但是存在一定的问题,那就是在短信内容中不能出现<>之类的括号,本文使用xml序列化器来解决
xml序列化器对象
XmlSerializer xs = Xml.newSerializer();
* 给序列化器设置输出流
File file = new File(Environment.getExternalStorageDirectory(), "backupsms.xml");
FileOutputStream fos = new FileOutputStream(file);
//给序列化器指定好输出流
xs.setOutput(fos, "utf-8");
* 开始生成xml文件
xs.startDocument("utf-8", true);
xs.startTag(null, "smss");
......
代码如下:
package com.wuyudong.createxml; import java.io.File; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; import org.xmlpull.v1.XmlSerializer; import com.wuyudong.createxml.domain.Sms; import com.wuyudong.createxml2.R; import android.os.Bundle; import android.os.Environment; import android.app.Activity; import android.util.Xml; import android.view.View; public class MainActivity extends Activity { List<Sms> message; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 创建10条虚拟短信 message = new ArrayList<Sms>(); for (int i = 0; i < 10; i++) { Sms sms = new Sms("第" + i + "条短信", System.currentTimeMillis() + "", "1", "" + i + i + i); message.add(sms); } } public void click(View v) { File file = new File(Environment.getExternalStorageDirectory(), "backup1.xml"); try { FileOutputStream fos = new FileOutputStream(file); // 获取xml序列化器 XmlSerializer xs = Xml.newSerializer(); xs.setOutput(fos, "utf-8"); //生成xml头 xs.startDocument("utf-8", true); //添加xml根节点 xs.startTag(null, "message"); for (Sms sms : message) { xs.startTag(null, "sms"); xs.startTag(null, "body"); xs.text(sms.getBody()); xs.endTag(null, "body"); xs.startTag(null, "date"); xs.text(sms.getDate()); xs.endTag(null, "date"); xs.startTag(null, "address"); xs.text(sms.getAddress()); xs.endTag(null, "address"); xs.startTag(null, "type"); xs.text(sms.getType()); xs.endTag(null, "type"); xs.endTag(null, "sms"); } xs.endTag(null, "message"); //生成xml头 xs.endDocument(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }