XmlPullParser解析xml文件

来源:互联网 发布:淘宝如何看评论销量 编辑:程序博客网 时间:2024/05/24 01:47

//即将要解析的xml文件格式是百度天气预报接口返回数据的XML形式,(这里展示一部分)感兴趣的朋友可以搜索一下,这里就不重复了


*********************************************************

//xml文件格式

*********************************************************


<weather_data>
<date>周二 06月06日 (实时:25℃)</date>
<dayPictureUrl>
http://api.map.baidu.com/images/weather/day/zhenyu.png
</dayPictureUrl>
<nightPictureUrl>
http://api.map.baidu.com/images/weather/night/zhenyu.png
</nightPictureUrl>
<weather>阵雨</weather>
<wind>东风微风</wind>
<temperature>34 ~ 25℃</temperature>

<weather_data>


*********************************************************

//首先我们根据要解析的xml文件创建对应的bean实体类

*********************************************************


package com.wjg.xml.entity;
/**
* xml对应的实体bean文件*/
public class Weatherforecast {

public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDayPictureUrl() {
return dayPictureUrl;
}
public void setDayPictureUrl(String dayPictureUrl) {
this.dayPictureUrl = dayPictureUrl;
}
public String getNightPictureUrl() {
return nightPictureUrl;
}
public void setNightPictureUrl(String nightPictureUrl) {
this.nightPictureUrl = nightPictureUrl;
}
public String getWeather() {
return weather;
}
public void setWeather(String weather) {
this.weather = weather;
}
public String getWind() {
return wind;
}
public void setWind(String wind) {
this.wind = wind;
}
public String getTemperature() {
return temperature;
}
public void setTemperature(String temperature) {
this.temperature = temperature;
}
private String date;
private String dayPictureUrl;
private String nightPictureUrl;
private String weather;
private String wind;
private String temperature;
public String toString() {  
        return "Person [date=" + date + ", dayPictureUrl=" + dayPictureUrl + ", nightPictureUrl=" + nightPictureUrl + ", weather=" + weather+", wind=" + wind+", temperature=" + temperature+"]";  
    }



}

********************************************************

接着我们创建解析XMLpullparser,本来要实现接口,懒得弄了,直接写成两个静态的方法

*******************************************************

public  class PollXmlService {  
    public  static final List<Weatherforecast> readXml(InputStream xml) throws Exception{  
        //通过XmlPullParserFactory获取XmlPullParser对象  
        //XmlPullParserFactory factory=XmlPullParserFactory.newInstance();  
        //XmlPullParser xParser=factory.newPullParser();  
          
        XmlPullParser xmlPullParser=Xml.newPullParser();  
        //为Pull解析器设置输入流和编码格式  
        xmlPullParser.setInput(xml, "UTF-8");  
        
        //获取XMl读取的位置  
        int eventType=xmlPullParser.getEventType();  
          
        List<Weatherforecast> persons=null;  
        Weatherforecast weatherforecast=null; 
        //只要没有到文档结束事件,一直循环
        while(eventType!=XmlPullParser.END_DOCUMENT){  
            switch (eventType) {
            // 判断当前事件是否为文档开始事件  
            case XmlPullParser.START_DOCUMENT:  
            //做初始化工作
                persons=new ArrayList<Weatherforecast>();  
                
                break;  
            // 判断当前事件是否为标签元素开始事件
            case XmlPullParser.START_TAG:  
                if(xmlPullParser.getName().equals("date")){  
                //bean实体为什么放在这里实例化,因为xml文件中有几天的天气数据,每一天对应一个weatherforecast对象
                weatherforecast=new Weatherforecast();
                    String str_temp=xmlPullParser.nextText();
                    weatherforecast.setDate(str_temp);
                }else if(xmlPullParser.getName().equals("dayPictureUrl")){  
                String str_temp=xmlPullParser.nextText();
                    weatherforecast.setDayPictureUrl(str_temp);
                }else if(xmlPullParser.getName().equals("nightPictureUrl")){  
                String str_temp=xmlPullParser.nextText();
                    weatherforecast.setNightPictureUrl(str_temp);
                }else if(xmlPullParser.getName().equals("weather")){  
                String str_temp=xmlPullParser.nextText();
                    weatherforecast.setWeather(str_temp);
                }else if(xmlPullParser.getName().equals("wind")){  
                String str_temp=xmlPullParser.nextText();
                    weatherforecast.setWind(str_temp);
                }else if(xmlPullParser.getName().equals("temperature")){  
                String str_temp=xmlPullParser.nextText();
                    weatherforecast.setTemperature(str_temp);
                }  
                break;
            // 判断当前事件是否为标签元素结束事件  
            case XmlPullParser.END_TAG:  
                if(xmlPullParser.getName().equals("temperature")){ 
                //把对象添加到list集合中 
                    persons.add(weatherforecast);  
                    //对象再置为空
                    weatherforecast=null;  
                }  
                break;  
            case XmlPullParser.END_DOCUMENT:  
                xml.close();  
            } 
            //进入下一个元素并触发相应事件 
            eventType=xmlPullParser.next();  
        }
        //返回list  
        return persons;  
    }  
    
    public static String serialize(List<Weatherforecast> weatherforecast) throws Exception {


// 由android.util.Xml创建一个XmlSerializer实例
XmlSerializer serializer = Xml.newSerializer();
//使用StringWriter 
StringWriter writer = new StringWriter();
// 设置输出方向为writer
serializer.setOutput(writer);
serializer.startDocument("UTF-8", true);
//总的标签即最外层嵌套的标签
serializer.startTag("", "weather_data");


for (Weatherforecast person : weatherforecast) {
//判断开始标签和结束标签
serializer.startTag("", "date");
serializer.text(person.getDate()+"");
serializer.endTag("", "date");

serializer.startTag("", "dayPictureUrl");
serializer.text(person.getDayPictureUrl() + "");
serializer.endTag("", "dayPictureUrl");

serializer.startTag("", "nightPictureUrl");
serializer.text(person.getNightPictureUrl() + "");
serializer.endTag("", "nightPictureUrl");

serializer.startTag("", "weather");
serializer.text(person.getWeather() + "");
serializer.endTag("", "weather");

serializer.startTag("", "wind");
serializer.text(person.getWind() + "");
serializer.endTag("", "wind");

serializer.startTag("", "temperature");
serializer.text(person.getTemperature() + "");
serializer.endTag("", "temperature");


}
serializer.endTag("", "weather_data");
serializer.endDocument();
//返回StringWriter
return writer.toString();
}
}

*****************************************************************

最后我们创建demo

*****************************************************************

public class TestXml extends AndroidTestCase{  
    private final static String TAG="TestXmlQAQ";  
    public void testReadXml() throws Exception{  
        /** 
         * xml文件放在src目录下,编译时会放在类路径下,所以通过类加载器的getResouceAsStream方法 
         * 可获得文件的输入流 
         */ 
    //从类的加载找不到xml文件,抛出空异常,暂时没有解决,换个方法:xml放在assets目录下
        //InputStream is=this.getContext().getClassLoader().getResourceAsStream("person.xml");  
   
    InputStream is = this.getContext().getResources().getAssets().open("weatherforecast.xml");
    //获取res/raw文件输入流:  InputStream is = getResources().openRawResource(R.raw.XXX); 
   
   
   
    /*//调用方法,执行读取操作  
        List<Weatherforecast> persons=PollXmlService.readXml(is);  
        for (Weatherforecast person : persons) {  
            //LogCat控制台输出person信息  
            Log.i(TAG, person.toString());  
        } */
        
        //调用方法,执行写操作 
        String xmlString=PollXmlService.serialize(PollXmlService.readXml(is));
        // 使用文件输出流
FileOutputStream fos = this.getContext().openFileOutput("NewFile.xml",Context.MODE_PRIVATE);
//写入xml文件
fos.write(xmlString.getBytes("UTF-8"));
    }  
}  

*********************************************************

要在配置文件添加相应的包进来(也不知道这中说法对不对,看个人理解吧)

进行的是测试所以要导入一些类似权限的东西

*********************************************************

*********************************************************

//首先我们根据要解析的xml文件创建对应的bean实体类

*********************************************************


 <uses-permission android:name="android.permission.INTERNET"/>

*********************************************************

//首先我们根据要解析的xml文件创建对应的bean实体类

*********************************************************


<instrumentation 
   android:name="android.test.InstrumentationTestRunner"
   android:targetPackage="com.wjg.xml">   
</instrumentation>

//由于只是简单的分开测试了两个方法,不足之处还望多多指教,至于XML文件存放的位置代码注释中有讲到,还有根据list生成的新的XML文件在DDMS data下对应包的文件夹下

*********************************************************

//首先我们根据要解析的xml文件创建对应的bean实体类

*********************************************************