Android using Pull parsing and generation XML

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

Can use SAX and DOM analysis of XML Java, although the Android can use this 2, but still recommended by Pull. Pull is simple to use, relatively high efficiency, Android is integrated with Pull, so do not need to use third party package.

Here for example, I want to XML documents to read and write the student information, firstly, I define a class of students, including ID, student number, name and age

public class Student {
	public Student() {};
	public Student(int id, int number, String name, int age) { = id;
		this.number = number; = name;
		this.age = age;

	private int id;
	private int number;
	private String name;
	private int age;
	public int getId() {
		return id;
	public int getNumber() {
		return number;
	public String getName() {
		return name;
	public int getAge() {
		return age;
	public void setId(int id) { = id;
	public void setNumber(int number) {
		this.number = number;
	public void setName(String name) { = name;
	public void setAge(int age) {
		this.age = age;
	public String toString() {
		return "Student [number=" + number + ", name=" + name + ", age=" + age
				+ "]";

To read the XML file content is this

<?xml version="1.0" encoding="UTF-8"?>
	<student id="1">
		<name>Zhang San</name>
	<student id="2">
		<name>Li Si</name>

Then I wrote a XmlHelper class, getStudes static methods, the method receives the input stream, returns a collection of student information

public static List<Student> getStudents(InputStream xml) throws Exception {
		List<Student> students = null;
		Student student = null;
		XmlPullParser parser = Xml.newPullParser(); //Get the Pull parser
		parser.setInput(xml, "UTF-8");	//Set the input, coded as UTF-8
		int event = parser.getEventType(); //Get event types, each read a location has relative event types
		while (XmlPullParser.END_DOCUMENT != event) {	//Not to the end of the document to read cycle
			switch (event) {
			case XmlPullParser.START_DOCUMENT: //This is the start of the document, we do some initial work in this place
				students = new ArrayList<Student>();
			case XmlPullParser.START_TAG:	//Label start event, label is above XML, <students> <student>, <number>, <name>, and <age>
				if (parser.getName().equals("student")) { //Read the student tags that below is the information I need.
					int id = Integer.valueOf(parser.getAttributeValue(0));
					student = new Student();
				if (null != student) { //To avoid a null pointer, to judge whether to continue
					if (parser.getName().equals("number")) {
						int number = Integer.valueOf(parser.nextText()); // nextText() Is a text label
					}else if (parser.getName().equals("name")) {
						String name = parser.nextText();
					}else if (parser.getName().equals("age")) {
						int age = Integer.valueOf(parser.nextText());
			case XmlPullParser.END_TAG:
				//Read </student> when a student information is read.
				if (parser.getName().equals("student")) {
					student = null;
			event =; //A read out, is the next, and so
		return students;

Read that, then write how to generate. The generate method, acceptance set and output student information flow
In fact, a good understanding, is in accordance with the order of a piece of information a piece of information to write down

public static void generate(List<Student> students, OutputStream os) throws Exception {
		XmlSerializer serializer = Xml.newSerializer(); //Get the serializer
		serializer.setOutput(os, "UTF-8"); //Set the output
		serializer.startDocument("UTF-8", true); //The start of the document.
		serializer.startTag(null, "students"); //The label began
		for (Student student : students) {
			serializer.startTag(null, "student"); //Sub label began
			serializer.attribute(null, "id", String.valueOf(student.getId())); //Specifies the label attribute, this is ID
			//The 3 is to generate student number, name and age
			serializer.startTag(null, "number");
			serializer.endTag(null, "number");
			serializer.startTag(null, "name");
			serializer.endTag(null, "name");
			serializer.startTag(null, "age");
			serializer.endTag(null, "age");
			serializer.endTag(null, "student"); //End Sub label
		serializer.endTag(null, "students"); //The tag end
		serializer.endDocument(); //The end of the document
		os.flush(); //If the incoming output stream is not a file, you must refresh buffer

Then I have to write a unit test to test both methods

public class XmlHelperTest extends AndroidTestCase {
	private static final String TAG = "XmlHelperTest";
	public void testGetStudents() throws Exception {
		InputStream xmlIstm = this.getClass().getClassLoader().getResourceAsStream("students.xml");
		List<Student> students = XmlHelper.getStudents(xmlIstm);
		for (Student student : students) {
			Log.i(TAG, student.toString());
	public void testGenerate() throws Exception {
		List<Student> students = new ArrayList<Student>();
		students.add(new Student(1, 13, "Xiaojian", 21));
		students.add(new Student(2, 16, "Dakang", 20));
		File xmlFile = new File(getContext().getFilesDir(), "students.xml");
		FileOutputStream fos = new FileOutputStream(xmlFile);
		try {
			XmlHelper.generate(students, fos);
			Log.i(TAG, "Generate XML file");
		} catch(Exception e) {
			Log.i(TAG, "Generate the XML file failed: " + e.getMessage());

The landlord had been writing C+ +, also scholarship Android soon, come on.
Long time no write blog, feeling, or should insist on writing.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Katherine at December 15, 2013 - 11:54 AM