从服务器上获取XML资源,并在客户端上解析下来,
实现的步骤如下:
1.pull 解析网络上XML文件的内容
1.新建一个URL链接对象、并打开链接(HttpURLConnection)
2.设置一些参数,比如链接超时,请求方式(GET、POST)等
3.得到xml的输入流getInputStream();
4.用pull解析XML文件
1.实例化一个newPullParser对象
2.得到解析的类型getEventType
3.从START_DOCUMENT、START_TAG、END_TAG、END_DOCUMENT对XML进行解析,返回解析的内容
5.解析过程中需要用到Bean的一些get、set、以及构造函数的一些方法
实现的效果如下:
这时候会出现以下异常:
Error parsing document. (position:line -1,column -1) caused by: org.apache.harmony.xml.ExpatParser$ParseException: At line 2,column 0: XML or text declaration not at start of entity; nested exception is:
产生异常的原因是因为:JSP代码中的<%@ page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>被放在最前面了,这样会导致XML前面出现空行,所以解析的时候会报-1行和-1列
在XML解析文档的时候默认的是从<?xml version="1.0" encoding="UTF-8"?>开始的
解决方法如下:
@H_403_50@<?xml version="1.0" encoding="UTF-8"?><%@ page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <newslist> <c:forEach items="${newes}" var="news"> <news id="${news.id}"> <title>${news.title}</title> <timelength>${news.timelength}</timelength> </news> </c:forEach> </newslist>客户端实现的代码:
bean的实现News的方法和解析的代码如下:public class NewsService { public static List<News> getLastNews() throws Exception { String path = "http://10.8.2.33/WebXMLDemo/ServletForXML"; HttpURLConnection connection = (HttpURLConnection) new URL(path) .openConnection(); connection.setConnectTimeout(5000); connection.setRequestMethod("GET"); if (connection.getResponseCode() == 200) { InputStream xml = connection.getInputStream(); return parseXML(xml); } return null; } private static List<News> parseXML(InputStream xml) throws Exception { List<News> newes = null; News news = null; // XmlPullParser pullParser = Xml.newPullParser(); XmlPullParser pullParser=XmlPullParserFactory.newInstance().newPullParser(); pullParser.setInput(xml,"UTF-8"); int event = pullParser.getEventType(); while (event != XmlPullParser.END_DOCUMENT) { switch (event) { case XmlPullParser.START_DOCUMENT: newes = new ArrayList<News>(); break; case XmlPullParser.START_TAG: if ("news".equals(pullParser.getName())) { int id = new Integer(pullParser.getAttributeValue(0)); news = new News(); news.setId(id); } if ("title".equals(pullParser.getName())) { news.setTitle(pullParser.nextText()); } if ("timelength".equals(pullParser.getName())) { news.setTimelength(new Integer(pullParser.nextText())); } break; case XmlPullParser.END_TAG: if ("news".equals(pullParser.getName())) { newes.add(news); news = null; } break; } event=pullParser.next(); } return newes; } }实现Activity的方法如下:
public class GetXMLDemoActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.list); ListView listView = (ListView) findViewById(R.id.list); String length = getResources().getString(R.string.length); try { List<News> newlist = NewsService.getLastNews(); List<HashMap<String,Object>> data = new ArrayList<HashMap<String,Object>>(); for (News news : newlist) { HashMap<String,Object> item = new HashMap<String,Object>(); item.put("id",news.getId()); item.put("title",news.getTitle()); item.put("timelength",length + news.getTimelength()); data.add(item); } SimpleAdapter adapter = new SimpleAdapter(this,data,R.layout.list_item,new String[] { "title","timelength" },new int[] { R.id.title,R.id.timelength }); listView.setAdapter(adapter); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
服务器端实现的代码如下:
实现请求的Servlet方法
public class ServletForXML extends HttpServlet { private static final long serialVersionUID = 1L; private XMLService newsService = new XMLServiceBean(); protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { doPost(request,response); } protected void doPost(HttpServletRequest request,IOException { List<News> newes = newsService.getLastNews(); request.setAttribute("newes",newes); request.getRequestDispatcher("/WEB-INF/page/news.jsp").forward(request,response); } }实现bean的业务方法和添加测试数据的方法如下
public class XMLServiceBean implements XMLService { @Override public List<News> getLastNews() { List<News> newes = new ArrayList<News>(); newes.add(new News(10,"wangjie",20)); newes.add(new News(45,"test",10)); newes.add(new News(89,"good",50)); return newes; } }原文链接:https://www.f2er.com/xml/300528.html