1 public Boolean SavePersonsToXml(List<Person> pList) 2 { 3 4 //new 一个创建xml的序列化对象 5 XmlSerializer xs = Xml.newSerializer(); 6 7 try { 8 9 //然后用文件初始化用于创建xml文件的序列化对象(此处记得添加2用户权限) 10 File file = new File(Environment.getExternalStorageDirectory(),"persons.xml"); 11 FileOutputStream fos = new FileOutputStream(file); 12 xs.setOutput(fos, "utf-8"); 13 14 //开始创建标签 15 xs.startDocument("utf-8", true); 16 xs.startTag(null, "persons"); 17 18 19 for(Person person:pList){ 20 21 xs.startTag(null, "person"); 22 xs.attribute(null, "id", person.getId()+""); 23 24 xs.startTag(null, "name"); 25 xs.text(person.getName()); 26 xs.endTag(null, "name"); 27 28 xs.startTag(null, "age"); 29 xs.text(person.getAge()+""); 30 xs.endTag(null, "age"); 31 32 xs.startTag(null, "sex"); 33 xs.text(person.getSex()); 34 xs.endTag(null, "sex"); 35 36 xs.endTag(null, "person"); 37 } 38 39 xs.endTag(null, "persons"); 40 xs.endDocument(); 41 42 fos.close(); 43 return true; 44 45 } catch (Exception e) { 46 // TODO Auto-generated catch block 47 e.printStackTrace(); 48 return false; 49 } 50 }
时间: 2024-10-11 03:49:18