学习用pull解析解析xml文件
发布时间:2020-12-16 05:18:04 所属栏目:百科 来源:网络整理
导读:博主我最近学习了下android的pull解析,大概解析代码如下: public class WeatherService {public static ListStudentInfo getWeatherInfo(InputStream is)throws Exception {// 1、新建一个解析器parserXmlPullParser parser = Xml.newPullParser();// 2、
博主我最近学习了下android的pull解析,大概解析代码如下: public class WeatherService { public static List<StudentInfo> getWeatherInfo(InputStream is) throws Exception { // 1、新建一个解析器parser XmlPullParser 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; } // 每次循环重新获取新的type type = 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(); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |