在android中使用Pull解析器生成xml文件

1:程序用到的Person类

public class Person {
	
	private Integer id;
	private String name;
	private Short age;
	
	public Person(){}

	public Person(Integer id, String name, Short age) {
		super();
		this.id = id;
		this.name = name;
		this.age = 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 Short getAge() {
		return age;
	}

	public void setAge(Short age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Person [age=" + age + ", id=" + id + ", name=" + name + "]";
	}

}
2:生成xml文件的程序

//使用Pull解析器生成xml文件
	public static void save(List<Person> persons, OutputStream outputStream) throws IllegalArgumentException, IllegalStateException, IOException {
		XmlSerializer serializer = Xml.newSerializer();
		serializer.setOutput(outputStream, "UTF-8");
		serializer.startDocument("UTF-8", 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());
			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();
	}


3:测试程序

        /*
	 * 测试使用Pull解析器建立xml文件
	 */
	public void testPullSavePersons() throws IllegalArgumentException, IllegalStateException, IOException {
		PullXMLService pullXMLService = new PullXMLService();
		try {
			FileOutputStream fileOutputStream = this.getContext().openFileOutput("persons.xml", Context.MODE_PRIVATE);
			
			List<Person> persons = new ArrayList<Person>();
			persons.add(new Person(10, "zhangsan", (short)10));
			persons.add(new Person(11, "lisi", (short)11));
			persons.add(new Person(12, "wangwu", (short)12));

			pullXMLService.save(persons, fileOutputStream);
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
	}


4:生成的xml文件persons.xml的内容如下

<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<persons>
	<person id="10">
		<name>zhangsan</name>
		<age>10</age>
	</person>
	<person id="11">
		<name>lisi</name>
		<age>11</age>
	</person>
	<person id="12">
		<name>wangwu</name>
		<age>12</age>
	</person>
</persons>





你可能感兴趣的:(在android中使用Pull解析器生成xml文件)