XmlPullParser 方式解析 XML 文档

XML 文件格式

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <persons>
  3. <person id="1">
  4. <name>张三</name>
  5. <age>22</age>
  6. </person>
  7. <person id="2">
  8. <name>李四</name>
  9. <age>20</age>
  10. </person>
  11. </persons>

XmlPullParser 方式解析 XML 文件

  1. import java.io.InputStream;
  2. import java.io.OutputStream;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import org.xmlpull.v1.XmlPullParser;
  6. import org.xmlpull.v1.XmlSerializer;
  7. import com.eboy.domain.Person;
  8. import android.util.Xml;
  9. public class PersonService {
  10. public static List<Person> getPersons(InputStream xml) throws Exception {
  11. List<Person> persons = null;
  12. Person person = null;
  13. XmlPullParser pullParser = Xml.newPullParser();
  14. pullParser.setInput(xml, "UTF-8"); // 为Pull解释器设置要解析的XML数据
  15. int event = pullParser.getEventType();
  16. while (event != XmlPullParser.END_DOCUMENT) {
  17. switch (event) {
  18. case XmlPullParser.START_DOCUMENT:
  19. persons = new ArrayList<Person>();
  20. break;
  21. case XmlPullParser.START_TAG:
  22. if ("person".equals(pullParser.getName())) {
  23. int id = Integer.valueOf(pullParser.getAttributeValue(0));
  24. person = new Person();
  25. person.setId(id);
  26. }
  27. if ("name".equals(pullParser.getName())) {
  28. String name = pullParser.nextText();
  29. person.setName(name);
  30. }
  31. if ("age".equals(pullParser.getName())) {
  32. int age = Integer.valueOf(pullParser.nextText());
  33. person.setAge(age);
  34. }
  35. break;
  36. case XmlPullParser.END_TAG:
  37. if ("person".equals(pullParser.getName())) {
  38. persons.add(person);
  39. person = null;
  40. }
  41. break;
  42. }
  43. event = pullParser.next();
  44. }
  45. return persons;
  46. }
  47. /**
  48. * 保存数据到xml文件中
  49. * @param persons
  50. * @param out
  51. * @throws Exception
  52. */
  53. public static void save(List<Person> persons, OutputStream out) throws Exception {
  54. XmlSerializer serializer = Xml.newSerializer();
  55. serializer.setOutput(out, "UTF-8");
  56. serializer.startDocument("UTF-8", true);
  57. serializer.startTag(null, "persons");
  58. for (Person person : persons) {
  59. serializer.startTag(null, "person");
  60. serializer.attribute(null, "id", person.getId().toString());
  61. serializer.startTag(null, "name");
  62. serializer.text(person.getName().toString());
  63. serializer.endTag(null, "name");
  64. serializer.startTag(null, "age");
  65. serializer.text(person.getAge().toString());
  66. serializer.endTag(null, "age");
  67. serializer.endTag(null, "person");
  68. }
  69. serializer.endTag(null, "persons");
  70. serializer.endDocument();
  71. out.flush();
  72. out.close();
  73. }
  74. }

(完)