在前面我们知道了怎样去解析xml文档,NOW如果让我们去生成xml文档怎么做呢?在这里其实有很多的方法可以去做例如我们可以再android中使用StringBuilder来组拼xml文档也可以使用DomAPI来生成xml文档,如果在像android这样的手机设备我们最好使用pull解析器去生成xml文档。那么下面就让我们来实现吧!
下面的业务类封装了生成xml文档过程
public class WriteXMLService {
public String WriteXml(List<Person> ls,Writer writer)
{
XmlSerializer serializer=Xml.newSerializer();
try {
serializer.setOutput(writer);
serializer.startDocument("UTF-8", true);//写<?xml version="1.0" encoding="UTF-8"?>
//第一个参数为命名空间,如果不使用命名空间,可以设置为null
serializer.startTag(null, "persons");//写根元素<persons>
for(Person person:ls)
{
serializer.startTag(null, "person");//写<person id="23">
serializer.attribute(null, "id", person.getId()+"");
serializer.startTag(null, "name");
serializer.text(person.getName());
serializer.endTag(null, "name");
serializer.startTag(null, "age");
serializer.text(person.getAge()+"");
serializer.endTag(null, "age");
serializer.endTag(null, "person");
}
serializer.endTag(null,"persons");
serializer.endDocument();
} catch (Exception e) {
e.printStackTrace();
}
return writer.toString();
}
}
下面这个是单元测试方法:
注意下面的几个函数在我前面解析xml函数中可以找到为了偷懒就直接拿过来用了:
//写xml文档
public void testWriteXml()
{
//先加载数据
DOMParsseService service = new DOMParsseService();
InputStream inStream = getClass().getClassLoader().getResourceAsStream("person.xml");
List<Person> persons = service.readXMLDOM(inStream);
/////////
// File writer=new File(Environment.getExternalStorageDirectory(),"writeperson.xml");
//FileOutputStream outputStream;
try {
FileOutputStream outputStream=getContext().openFileOutput("writeperson.xml",Context.MODE_PRIVATE);
//outputStream = new FileOutputStream(writer);
OutputStreamWriter outputStreamWriter=new OutputStreamWriter(outputStream);
BufferedWriter bufferedWriter=new BufferedWriter(outputStreamWriter);
WriteXMLService xmlService=new WriteXMLService();
xmlService.WriteXml(persons, bufferedWriter);
bufferedWriter.flush();
bufferedWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}