第一步:解析文档为一下文档
<?xml version="1.0" encoding="UTF-8"?> <students> <student id="A001"> <name>zhangsan</name> <sex>male</sex> <age>12</age> <address>beijing</address> </student> <student id="A002"> <name>lisi</name> <sex>male</sex> <age>13</age> <address>beijing</address> </student> </students>
第二步:下载xml文档
public static InputStream downloader(String path) { InputStream inputStream = null; try { URL url = new URL(path); HttpURLConnection httpURLConnection = (HttpURLConnection) url .openConnection(); inputStream = httpURLConnection.getInputStream(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return inputStream; }
第三步:解析过程
private void xmlPullParser(InputStream inputStream) { try { // 定义SAXParserFaco xmlPullParserFactory = XmlPullParserFactory.newInstance(); xmlPullParser = xmlPullParserFactory.newPullParser(); // xmlPullParser = Xml.newPullParser(); xmlPullParser.setInput(inputStream, "UTF-8"); int eventType = xmlPullParser.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { currentTagName = xmlPullParser.getName(); switch (eventType) { case XmlPullParser.START_DOCUMENT: list = new ArrayList<Student>(); break; case XmlPullParser.START_TAG: if ("student".equals(currentTagName)) { // 实例化Student对象 student = new Student(); // 获取属性ID student.setId(xmlPullParser.getAttributeValue(0)); } else if ("name".equals(currentTagName)) { student.setName(xmlPullParser.nextText()); } else if ("sex".equals(currentTagName)) { student.setSex(xmlPullParser.nextText()); } else if ("age".equals(currentTagName)) { student.setAge(Integer.parseInt(xmlPullParser .nextText())); } else if ("address".equals(currentTagName)) { student.setAddress(xmlPullParser.nextText()); } break; case XmlPullParser.END_TAG: list.add(student); printout(student); break; case XmlPullParser.END_DOCUMENT: System.out.println("end_document"); break; default: break; } eventType = xmlPullParser.next(); } } catch (Exception e) { // TODO: handle exception } }
实体类参考
package com.bjhksj.pull; public class Student { private String id; public String getId() { return id; } public void setId(String id) { this.id = id; } private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } private int age; public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } private String sex; public int getAge() { return age; } public void setAge(int age) { this.age = age; } private String address; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }