Android开发之XML的创建和解析

参考:http://blog.csdn.net/pi9nc/article/details/9320413

 

XML文件的解析,代码:

 1 public void click(View v) {
 2   InputStream is = getClassLoader().getResourceAsStream("weather.xml");
 3   //获取到XMLPullParse接口的对象
 4   XmlPullParser xpp = Xml.newPullParser();
 5   try {
 6    //设置输出流及编码
 7    xpp.setInput(is, "utf-8");
 8    //获取到节点的类型,START_DOCUMENT=0,END_DOCUMENT=1,START_TAG=2,END_TAG=3,TEXT=4
 9    int type = xpp.getEventType();
10    CityBean city = null;
11    //当前节点不是END_DOCUMENT的话,就一直循环遍历XML文件
12    while (type!=XmlPullParser.END_DOCUMENT) {
13     //使用switch判断type类型
14     switch (type) {
15     //type为2的情况下,进入START_TAG
16     case XmlPullParser.START_TAG:
17      //获取当前节点的名字是weather
18      if ("weather".equals(xpp.getName())) {
19       //city的集合
20       cityList=new ArrayList<>();
21      }else if ("city".equals(xpp.getName())) {
22       city = new CityBean();
23      }else if ("name".equals(xpp.getName())) {
24       String name = xpp.nextText();
25       city.setName(name);
26      }else if ("temp".equals(xpp.getName())) {
27       String temp = xpp.nextText();
28       city.setTemp(temp);
29      }else if ("pm".equals(xpp.getName())) {
30       String pm = xpp.nextText();
31       city.setPm(pm);
32      }
33      break;
34     case XmlPullParser.END_TAG:
35      if ("city".equals(xpp.getName())) {
36       cityList.add(city);
37      }
38      break;
39     default:
40      break;
41     }
42     //把解析的指针移动到下一个节点
43     type=xpp.next();
44    }
45    for (CityBean c1 : cityList) {
46     System.out.println(c1.toString());
47    }
48   } catch (Exception e) {
49    e.printStackTrace();
50   }    
51  }

 

XML文件的创建,代码:

 1 File file = new File(Environment.getExternalStorageDirectory(),"info3.xml");
 2    XmlSerializer xml = Xml.newSerializer();
 3    try {
 4     FileOutputStream fos = new FileOutputStream(file);
 5     xml.setOutput(fos, "utf-8");
 6     xml.startDocument("utf-8", true);
 7     xml.startTag(null, "message");
 8     for (SmsBean smsBean : smsList) {
 9      xml.startTag(null, "sms");
10      xml.startTag(null, "body");
11      xml.text(smsBean.getBody());
12      xml.endTag(null, "body");
13      xml.startTag(null, "address");
14      xml.text(smsBean.getAddress());
15      xml.endTag(null, "address");
16      xml.startTag(null, "date");
17      xml.text(smsBean.getDate());
18      xml.endTag(null, "date");
19      xml.startTag(null, "type");
20      xml.text(smsBean.getType());
21      xml.endTag(null, "type");
22      xml.endTag(null, "sms");
23     }
24     xml.endTag(null, "message");
25     xml.endDocument();
26     fos.close();
27    } catch (Exception e) {
28 
29     e.printStackTrace();
30 }

 

posted @ 2016-03-24 15:41  熠然  阅读(814)  评论(0编辑  收藏  举报