Android中使用XmlPullParser操作简单的xml文件

来源:互联网 发布:qq群成员提取软件 编辑:程序博客网 时间:2024/05/17 09:00

在开发的过程中,如果需要保存少量数据,可以使用xml来保存,尽量不使用数据库。解析xml的方式有Dom,Sax,Dom4j等,今天要学的是XmlPullParser。

我们先来看看要解析的文件格式是什么


XmlPullParser是从上到下对xml文件进行解析的,跟我们写xml文件的顺序是一样的,顺序获取每个节点的值,一次解析。

其实用法很简单,看代码的注释就应该知道怎么使用啦

首先是City这个bean

public class City {private String country;private String city;private String sights;public String getCountry() {return country;}public void setCountry(String country) {this.country = country;}public String getCity() {return city;}public void setCity(String city) {this.city = city;}public String getSights() {return sights;}public void setSights(String sights) {this.sights = sights;}@Overridepublic String toString() {return "City [country=" + country + ", city=" + city + ", sights="+ sights + "]";}}

接着是解析操作咯

private List<City> getBean(InputStream inStream) throws Exception {List<City> cities = null;//首先获取一个解析器对象,然后规定字符集XmlPullParser pullParser = Xml.newPullParser();pullParser.setInput(inStream, "UTF-8");//获取当前Element的类型 (START_TAG, END_TAG, TEXT......)int eventType = pullParser.getEventType();City city = null;//当它还没解析到文档的结束Elementwhile (eventType != XmlPullParser.END_DOCUMENT) {switch (eventType) { //文档的开始case XmlPullParser.START_DOCUMENT:cities = new ArrayList<City>();break;//Element的开始节点,比如 <html> </html>  <html>即是开始的Element,</html>为结束Elementcase XmlPullParser.START_TAG:/** * 通过获取pullParser.getName()获取当前节点的值, <city country="Greece"> pullParser.getAttributeValue(0) * 获取的是city这个节点的第一个属性即country的值 */if( "city".equals(pullParser.getName()) ){city = new City();city.setCountry(pullParser.getAttributeValue(0));}if( "name".equals(pullParser.getName()) ){city.setCity(pullParser.nextText());}if( "sights".equals(pullParser.getName())){city.setSights(pullParser.nextText());}break;//结束节点case XmlPullParser.END_TAG:if( "city".equals(pullParser.getName()) ){//将结果添加到集合,并且将bean对象置为空cities.add(city);city = null;}break;default:break;}//需要调用这个方法,解析才会指向下一个节点eventType = pullParser.next();}return cities;}
既然有了解析了,那应该会有写的方法

private void save(List<City> cities, OutputStream ou) throws Exception{//获取写对象XmlSerializer serializer = Xml.newSerializer();//设置字符集serializer.setOutput(ou, "UTF-8");//设置文档开头声明,类似于<?xml version="1.0" encoding="utf-8"?>serializer.startDocument("UTF-8", true);//写入一个开始的Elementserializer.startTag(null, "cities");for(City city:cities){//写下一个Element,并添加属性serializer.startTag(null, "city");serializer.attribute(null, "country", city.getCountry());//写下一个Element,并添加包裹的文本serializer.startTag(null, "name");serializer.text(city.getCity());serializer.endTag(null, "name");serializer.startTag(null, "sights");serializer.text(city.getSights());serializer.endTag(null, "sights");//结束Elementserializer.endTag(null, "city");}//最外层的结束Elementserializer.endTag(null, "cities");//完成xml的写入操作serializer.endDocument();//刷新输出流ou.flush();ou.close();}




0 0
原创粉丝点击