doman类名为person.xml
package cn.itcast.doman;
public class Person {
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
生成xml方法类
public class XmlService {
public static void save(List<Person> persons,OutputStream outputStream) throws Exception{
XmlSerializer serializer = Xml.newSerializer();
serializer.setOutput(outputStream, "utf-8");
serializer.startDocument("UTF-8", true); //true表示生成单独文件
serializer.startTag(null, "persons");
for (Person person : persons) {
serializer.startTag(null, "person");
serializer.attribute(null, "id", person.getId().toString());
serializer.startTag(null, "name");
serializer.text(person.getName().toString());
serializer.endTag(null, "name");
serializer.startTag(null, "age");
serializer.text(person.getAge().toString());
serializer.endTag(null, "age");
serializer.endTag(null, "person");
}
serializer.endTag(null, "persons");
serializer.endDocument();
outputStream.flush();
outputStream.close();
}
}
测试类
public class TestXml extends AndroidTestCase{
public void TestXmlOne() throws Exception{
File file = new File(getContext().getFilesDir(), "Person.xml");
OutputStream outputStream = new FileOutputStream(file);
List<Person> persons = new ArrayList<Person>();
Person person = new Person();
person.setId(23);
person.setName("li");
person.setAge(21);
persons.add(person);
person = new Person();
person.setId(27);
person.setName("yuan");
person.setAge(21);
persons.add(person);
XmlService.save(persons, outputStream);
}
}