1 一个示例用的xml文件:person.xml
<?xml version="1.0" encoding="UTF-8"?> <persons> <person id="111"> <name>tom</name> <age>230</age> </person> <person id="222"> <name>jerry</name> <age>233</age> </person> </persons>
2 新建一个实体类:Person.java
package com.example.xml_saxparser; 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 Person( String name, Short age) { super(); 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 [id=" + id + ", name=" + name + ", age=" + age + "]"; } }
3 解析的关键类:PullParser
package com.example.xml_pullparser; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.annotation.SuppressLint; import android.util.Xml; import com.example.xml_saxparser.Person; public class PullPaser { @SuppressLint("UseValueOf") public static List<Person> getPerson(InputStream in) throws Exception{ Person person = null; List<Person> persons = null; XmlPullParser pullParser = Xml.newPullParser(); pullParser.setInput(in, "UTF-8"); int event = pullParser.getEventType(); while(event != XmlPullParser.END_DOCUMENT){ switch(event){ case XmlPullParser.START_DOCUMENT: persons = new ArrayList<Person>(); break; case XmlPullParser.START_TAG: if("person".equals(pullParser.getName())){ int id = new Integer(pullParser.getAttributeValue(0)); person = new Person(); person.setId(id); } if(person!= null){ if("name".equals(pullParser.getName())){ person.setName(pullParser.nextText()); } if("age".equals(pullParser.getName())){ person.setAge(new Short(pullParser.nextText())); } } break; case XmlPullParser.END_TAG: if("person".equals(pullParser.getName())){ persons.add(person); person = null; } break; } event = pullParser.next(); } return persons; } }
4 单元测试Pull解析,看看效果吧。怎么单元测试,前面文章有说明。
package com.example.xml_pullparser; import java.io.InputStream; import java.util.List; import android.test.AndroidTestCase; import android.util.Log; import com.example.xml_saxparser.MainActivity; import com.example.xml_saxparser.Person; public class PullJUnitTest extends AndroidTestCase { public void testPullgetPersons() throws Exception{ InputStream in = MainActivity.class.getClassLoader().getResourceAsStream("person.xml"); List<Person> persons = PullPaser.getPerson(in); in.close(); for(Person p : persons){ Log.i("Person", p.toString()); } } }