保存代码:
/**
* 保存数据到XML文件中
* @param persons
* @param out
* @throws Exception
*/
public void save(List<person> persons,OutputStream out) throws Exception{
XmlSerializer ser=Xml.newSerializer();
ser.setOutput(out, "UTF-8");
ser.startDocument("UTF-8",true);
//主信息
ser.startTag(null, "persons");
for(person item: persons)
{
//明细信息
ser.startTag(null, "person");
ser.attribute(null,"id",String.valueOf(item.getId()));
//Name
ser.startTag(null, "name");
ser.text(item.getName());
ser.endTag(null, "name");
//age
ser.startTag(null, "age");
ser.text(item.getName());
ser.endTag(null, "age");
ser.endTag(null, "person");
}
ser.endTag(null, "persons");
ser.endDocument();
out.flush();
out.close();
}
调用方法:
/**
* 信息写入XML中
* @param p
* @throws Exception
*/
private void outXml() throws Exception{
personservice p=new personservice();
List<person> pl=new ArrayList<person>();pl.add(new person(43,"zhangxx",80));
pl.add(new person(12,"lili",20));
pl.add(new person(78,"xiaoxiao",8));
File xmlFile=new File(this.getFilesDir(),"itcast.xml");
FileOutputStream out=new FileOutputStream(xmlFile);
p.save(pl, out);
}