学习用pull解析解析xml文件

来源:互联网 发布:python import math 编辑:程序博客网 时间:2024/06/05 10:48

博主我最近学习了下android的pull解析,大概解析代码如下:

public class WeatherService {public static List<StudentInfo> getWeatherInfo(InputStream is)throws Exception {// 1、新建一个解析器parserXmlPullParser parser = Xml.newPullParser();// 2、初始化解析器parser.setInput(is, "utf-8");// 3、解析xml文件int type = parser.getEventType();List<StudentInfo> weatherInfos = null; // 初始化weatherInfos列表StudentInfo studentInfo = null;while (type != XmlPullParser.END_DOCUMENT) {switch (type) {case XmlPullParser.START_TAG:// 全局开始的标签if ("resources".equals(parser.getName())) { // 根标签// 创建一个weatherInfos列表weatherInfos = new ArrayList<StudentInfo>();} else if ("city".equals(parser.getName())) { // 子标签// 创建一个weatherInfo实例studentInfo = new StudentInfo();String id = parser.getAttributeValue(0);studentInfo.setId(Integer.parseInt(id));} else if ("name".equals(parser.getName())) {String name = parser.nextText();studentInfo.setName(name);} else if ("color".equals(parser.getName())) {String color = parser.nextText();studentInfo.setColor(color);} else if ("class".equals(parser.getName())) {String classs = parser.nextText();studentInfo.setClasss(classs);} else if ("sex".equals(parser.getName())) {String sex = parser.nextText();studentInfo.setSex(sex);}break;case XmlPullParser.END_TAG:// 一个城市的信息 已经处理完毕weatherInfos.add(studentInfo);studentInfo = null;// 对象置为null 垃圾回收机制break;}// 每次循环重新获取新的typetype = parser.next();}return weatherInfos;}}


另外需做的工作是:

1、另建一个StudentInfo的类有如下属性:

private String name;private String color;private String sex;private String classs;private int id;
2、在主函数:

protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.pull);tv_text = (TextView) findViewById(R.id.tv_text);List<StudentInfo> studentInfo;try {// 文件在类路径下 采用类加载器,string.xml在src目录底下studentInfo = WeatherService.getWeatherInfo(PullActivity.class.getClassLoader().getResourceAsStream("string.xml"));//用StringBuffer加载字符串StringBuffer sb = new StringBuffer();for (StudentInfo info : studentInfo) {String str = info.toString();sb.append(str);sb.append("\n");}tv_text.setText(sb.toString());} catch (Exception e) {Toast.makeText(getApplicationContext(), "解析失败", 0).show();e.printStackTrace();}