将实体类转成XML文件以流的形式输出
实体类:
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;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
public Person(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
public Person(){}
}
转换成后的XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person id="23">
<name>liming</name>
<age>30</age>
</person>
<person id="20">
<name>zhangxiaoxiao</name>
<age>25</age>
</person>
</persons>
/**
* 保存数据
* @param persons 数据
* @param out 输出方向
* @throws Exception
*/
public static void save(List<Person> persons, OutputStream out) throws Exception{
XmlSerializer serializer = Xml.newSerializer(); //得到序列化器
serializer.setOutput(out, "UTF-8"); //设置输出的方向以及编码方式,可以使文件或者网络
serializer.startDocument("UTF-8", true); //是否单独存在,不依赖别的文件
serializer.startTag(null, "persons"); //生成"persons"节点,null表示没有命名空间
for(Person person : persons){ //迭代集合得到每一个元素
serializer.startTag(null, "person");
serializer.attribute(null, "id", person.getId().toString()); //生成属性,名称和值
serializer.startTag(null, "name"); //开始节点
serializer.text(person.getName()); //设置内容
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();
out.flush();
out.close();
}
}