安卓下pull解析

时间:2021-12-17 18:01:38

 public void parseSMS(View v){
    	ArrayList<SMS> SMSs = null;
    	SMS sms = null;
    	//获取xml解析器
    	XmlPullParser pullParser = Xml.newPullParser();
    	//设置一个输入
    	try {
			pullParser.setInput(openFileInput("sms.xml"), "utf-8");
			//获取事件类型
			int eventType = pullParser.getEventType();
			//只要没解析到文档结束就一直解析
			while(eventType!= XmlPullParser.END_DOCUMENT){
				switch (eventType) {
				case XmlPullParser.START_TAG:
					if("SMSList".equals(pullParser.getName())){
						//创建集合
						SMSs = new ArrayList<SMS>();
					}else if("SMS".equals(pullParser.getName())){
						//创建对象
						sms = new SMS();
					}else if("from".equals(pullParser.getName())){
						//保存from属性
						sms.from = pullParser.nextText();
					}else if("content".equals(pullParser.getName())){
						//保存content属性
						sms.content = pullParser.nextText();
					}else if("time".equals(pullParser.getName())){
						//保存time属性
						sms.time = pullParser.nextText();
					}
					
					break;

				case XmlPullParser.END_TAG:
					if("SMS".equals(pullParser.getName())){
						//把对象添加到集合
						SMSs.add(sms);
					}
					break;
				}
				
				eventType = pullParser.next();
			}
			for(SMS sms1:SMSs){
				System.out.println(sms1);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    }