首先需要导入jar包:kxml2-2.2.2.jar
例程:
main:
/** * pull解析 * * @author my * */ public class DemoParserStudent { public static void main(String[] args) { try { // 1.创建解析器工厂对象 XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); // 2.创建解析器对象 XmlPullParser parser = factory.newPullParser(); // 3.指定数据源 parser.setInput(new FileReader("Students.xml")); // 4.获得响应码 int code = parser.getEventType(); Student s = null; List<Student> list = null; while (code != parser.END_DOCUMENT) { String name = parser.getName();// 获得标签名称 switch (code) { case XmlPullParser.START_TAG: if ("Students".equals(name)) { list = new ArrayList<Student>(); } else if ("Student".equals(name)) { s = new Student(); } else if ("name".equals(name)) { s.setName(parser.nextText()); } else if ("age".equals(name)) { s.setAge(new Integer(parser.nextText())); } else if ("sex".equals(name)) { s.setSex(parser.nextText()); } break; case XmlPullParser.END_TAG: if ("Student".equals(name)) { list.add(s); } break; } code = parser.next(); } for (Student student : list) { System.out.println(student); } } catch (XmlPullParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Student:
package com.qf.PullParser; public class Student { String no; String name; int age; String sex; public String getNo() { return no; } public void setNo(String no) { this.no = no; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } @Override public String toString() { return "Student [no = " + no + " name=" + name + ", age=" + age + ", sex=" + sex + "]"; } }