XMl解析之Pull解析

HttpUtils:

package cn.qf.parser;


import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/**
 * HttpClient请求网络 获取XML数据
 * 
 * @author my
 *
 */
public class HttpUtils {
    /**
     * Http请求网络获取xml数据
     * 下载图片
     * @param path
     */
    public static void downLoadImg(String path) {
        BufferedOutputStream bos = null;
        try {
            // 1.创建HttpCLient对象
            HttpClient httpClient = new DefaultHttpClient();
            // 2.创建请求对象 指定地址
            HttpGet htpGet = new HttpGet(path);
            // 3.执行请求 获得HttpResponse对象
            HttpResponse response = httpClient.execute(htpGet);
            // 4.获得响应码
            int code = response.getStatusLine().getStatusCode();
            if (code == 200) {
                // 获得响应的HttpEntity对象
                HttpEntity entity = response.getEntity();
                String name = path.substring(path.lastIndexOf("/") + 1);
                bos = new BufferedOutputStream(new FileOutputStream(name));
                bos.write(EntityUtils.toByteArray(entity));
                bos.flush();
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 从网络下载Xml文件
     * @param path
     * @return
     */
    public static String getXMLByInternet(String path) {
        try {
            // 1.创建httpClient对象
            HttpClient httpClient = new DefaultHttpClient();
            // 2.创建请求对象 指定地址
            HttpGet httpGet = new HttpGet(path);
            // 3.执行请求,获得HttpResponse对象
            HttpResponse response = httpClient.execute(httpGet);
            // 4.获得响应码
            int code = response.getStatusLine().getStatusCode();
            if (code == 200) {
                // 获得响应的httpEntity对象__客户端服务端传递的载体
                HttpEntity entity = response.getEntity();
                return EntityUtils.toString(entity, "GBK");
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }
}

ParserDemo.java

package com.qf.PullParser4;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

/**
 * http://api.map.baidu.com/telematics/v3/weather?location=北京&output=xml&ak=
 * mXBIDrvTOwwmYaTtN03Lo0j2 请求上述接口,使用pull解析<date>字段和<dayPictureUrl>字段,并把
 * <dayPictureUrl>字段对应的图片下载到本地, 展示到jsp页面
 * 
 * @author my
 *
 */
class WeatherDate {
    private String date;
    private String dayPictureUrl;

    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;
    }

    @Override
    public String toString() {
        return "WeatherDate [date=" + date + ", dayPictureUrl=" + dayPictureUrl + "]";
    }

}

public class parserDemo {
    public static void main(String[] args) {
        String xml = HttpUtils.getXMLByInternet(
                "http://api.map.baidu.com/telematics/v3/weather?location=北京&output=xml&ak=mXBIDrvTOwwmYaTtN03Lo0j2");
        System.out.println(xml);
        try {
            // 创建解析器工厂对象
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            // 创建解析器
            XmlPullParser parser = factory.newPullParser();
            // 设置数据源,
       //StringReader 是Reader的子类
       // StringReader 的数据源是String类型的字符串
         parser.setInput(new StringReader(xml));
            // 得到响应码
            int code = parser.getEventType();
            WeatherDate weatherDate = null;
            List<WeatherDate> list = null;
            String temp = "";
            while (code != XmlPullParser.END_DOCUMENT) {
                String name = parser.getName();
                switch (code) {
                case XmlPullParser.START_TAG:
                    if ("weather_data".equals(name)) {
                        list = new ArrayList<>();
                        temp = "weather";
                    } else if ("date".equals(name) && "weather".equals(temp)) {
                        weatherDate = new WeatherDate();
                        weatherDate.setdate(parser.nextText());
                    } else if ("dayPictureUrl".equals(name)) {
                        String path = parser.nextText();
                        weatherDate.setDayPictureUrl(path);
                        list.add(weatherDate);
                        // 下载图片
                        HttpUtils.downLoadImg(path);
                    }
                    break;
                default:
                    break;
                }
                code = parser.next();
            }
            for (WeatherDate weatherDate2 : list) {
                System.out.println(weatherDate2);
            }

        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}
原文地址:https://www.cnblogs.com/fangg/p/5723026.html