首先定义一个信息类Message
public class Message {
private String address;
private String body;
private String date;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
然后在布局中添加一个按钮,并设置点击事件
public class MainActivity extends Activity {
private List<Message> msgList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
msgList = new ArrayList<Message>();
for (int i = 0; i < 10; i++) {
Message msg = new Message();
msg.setAddress("1008" + i);
msg.setBody("abb" + i);
msg.setDate("2018" + i);
msgList.add(msg);
}
}
public void Click(View v) {
try {
XmlSerializer serializer = Xml.newSerializer();
File file = new File(Environment.getExternalStorageDirectory(),"xx");
FileOutputStream fos = new FileOutputStream(file);
serializer.setOutput(fos, "utf-8");
serializer.startDocument("utf-8", true);
serializer.startTag(null, "root");
for (Message msg : msgList) {
serializer.startTag(null, "msg");
serializer.startTag(null, "Address");
serializer.text(msg.getAddress());
serializer.endTag(null, "Address");
serializer.startTag(null, "body");
serializer.text(msg.getBody());
serializer.endTag(null, "body");
serializer.startTag(null, "date");
serializer.text(msg.getDate());
serializer.endTag(null, "date");
serializer.endTag(null, "msg");
}
serializer.endTag(null, "root");
serializer.endDocument();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}