Android利用pull解析器生成xml

来源:互联网 发布:淘宝直通车怎么找 编辑:程序博客网 时间:2024/09/21 09:04

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);}}


 

欢迎学习,有不懂或错误的地方可以指出,谢谢~~共同学习共同提升~~

 

原创粉丝点击