码迷,mamicode.com
首页 > 移动开发 > 详细

Android数据转化为Xml形式给客户端及客户端使用xml数据

时间:2015-03-30 16:24:10      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:xml解析   生成xml文件   

(1)创建实体类News

public class News {
    private Integer id;
    private String title;
    private Integer timelength;

    public News(Integer id, String title, Integer timelength) {
        this.id = id;
        this.title = title;
        this.timelength = timelength;
    }
    //get、set方法
}

(2)面向接口编程所创建的接口可接口的实现类:

public interface VideoNewsService {
    /**
     * 获取最新的视频资讯
     * @return
     */
    public List<News> getLastNews();

}

接口的实现类,用于加入一些假数据

public class VideoNewsServiceBean implements VideoNewsService {

    public List<News> getLastNews(){
        List<News> newes = new ArrayList<News>();
        newes.add(new News(90, "喜羊羊与灰太狼全集", 78));
        newes.add(new News(10, "实拍舰载直升东海救援演习", 28));
        newes.add(new News(56, "喀麦隆VS荷兰", 70));
        return newes;
    }
}

(3)通过servlet返回数据大客户端

public class ListServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private VideoNewsService service = new VideoNewsServiceBean();

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        List<News> videos = service.getLastNews();
        request.setAttribute("videos", videos);
        //重定向一个jsp界面,当客户端请求的时候返回的是该jsp页面数据
        request.getRequestDispatcher("/WEB-INF/page/videonews.jsp").forward(request, response);
    }
}

(4)生成xml文件的jsp页面(这里返回的为xml文件所以contentType=”text/xml”)

<%@ page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<?xml version="1.0" encoding="UTF-8"?>
<videonews>
<c:forEach items="${videos}" var="video">
    <news id="${video.id}">
        <title>${video.title}</title>
        <timelength>${video.timelength}</timelength>
    </news>
    </c:forEach>
</videonews>

(5)在客户端中使用xml文件
同样的客户端同样需要一个News实体类,这里省略
创建一个service类用于解析xml和返回xml文件数据

public class VideoNewsService {
    /**
     * 获取最新的视频资讯
     */
    public static List<News> getLastNews() throws Exception{
        String path = "请求servlet的url";
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        if(conn.getResponseCode() == 200){
            InputStream inStream = conn.getInputStream();
            return parseXML(inStream);
        }
        return null;
    }
    /**
     * 解析服务器返回的xml数据
<?xml version="1.0" encoding="UTF-8" ?> 
<videonews>
  <news id="35">
  <title>喜羊羊与灰太狼全集</title> 
  <timelength>90</timelength> 
  </news>
 <news id="12">
  <title>老张与灰太狼</title> 
  <timelength>20</timelength> 
  </news>
 <news id="56">
  <title>老方与LILI</title> 
  <timelength>30</timelength> 
  </news>
</videonews>
     */
    private static List<News> parseXML(InputStream inStream) throws Exception {
        List<News> newses = new ArrayList<News>();
        News news = null;
        XmlPullParser parser = Xml.newPullParser();
        parser.setInput(inStream, "UTF-8");
        int event = parser.getEventType();
        //对xml解析器的事件进行判断
        while( event != XmlPullParser.END_DOCUMENT){
            switch (event) {
            case XmlPullParser.START_TAG:
                if("news".equals(parser.getName())){
                    int id = new Integer(parser.getAttributeValue(0));
                    news = new News();
                    news.setId(id);
                }else if("title".equals(parser.getName())){
                    news.setTitle(parser.nextText());
                }else if("timelength".equals(parser.getName())){
                    news.setTimelength(new Integer(parser.nextText()));
                }
                break;

            case XmlPullParser.END_TAG:
                if("news".equals(parser.getName())){
                    newses.add(news);
                    news = null;
                }
                break;
            }
            event = parser.next();
        }
        return newses;
    }
}

(6)在Mainactivity.java文件中使用(这里是为一个listview设置值)

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ListView listView = (ListView) this.findViewById(R.id.listView);
        try {
            List<News> videos = VideoNewsService.getLastNews();//需修改成你本机的Http请求路径
            List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();
            for(News news : videos){
                HashMap<String, Object> item = new HashMap<String, Object>();
                item.put("id", news.getId());
                item.put("title", news.getTitle());
                item.put("timelength", getResources().getString(R.string.timelength)
                        + news.getTimelength()+ getResources().getString(R.string.min));
                data.add(item);
            }
            SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item,
                    new String[]{"title", "timelength"}, new int[]{R.id.title, R.id.timelength});
            listView.setAdapter(adapter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

到此完成操作

Android数据转化为Xml形式给客户端及客户端使用xml数据

标签:xml解析   生成xml文件   

原文地址:http://blog.csdn.net/xlgen157387/article/details/44752509

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!