好久不碰XML解析,在此写了个小的demo来温习一下解析XML,其中我用的Pull来解析XML,XML文件存放在tomcat服务器,服务器端采用SSH框架编码完成,由安卓端通过http的GET请求获取到xml,之后就是解析啦,解析完将所有数据存放在实体类中,接下来就是将数据显示在ListView上面了。demo虽小,但其中遇到一些问题卡住我半天,下面就来看看吧。服务器的搭建比较简单了,其中在action中处理安卓端的get请求,将person.xml以字节流的方式返回给安卓端.
action中代码:
//获取xml数据
public String getXmlData(){
try {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset:UTF-8");
response.setCharacterEncoding("UTF-8");
List persons=personBiz.getXmlData();
/*for (Person person : persons) {
System.out.println(person);
}*/
request.setAttribute("persons", persons);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "success";
}
dao层接口代码:
//查询所有xml数据
public List getXmlData();
dao层实现类代码:
@Override
public List getXmlData() {
List lists=getSession().createQuery("from Person").list();
return lists;
}
struts.xml中配置action:
name="getXmlData" class="personAction" method="getXmlData">
<result name="success">/list.jspresult>
服务器端页面请求:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title heretitle>
head>
<body>
<center>
<a href="getXmlData.action">解析XML数据a>
center>
body>
html>
服务器端页面返回结果:
<%@ page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<persons><c:forEach var="p" items="${persons}">
<person pid="${p.pid}">
<pname>${p.pname}pname>
<page>${p.page}page>
person>
c:forEach>
persons>
安卓端http的GET请求获取到xml,并解析,将数据存放到实体类中:
package com.example.android_parsexml;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ListView lv_main_list;
private List personList = new ArrayList();
private ProgressDialog progressDialog;
private MyAdapter myAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取listview
lv_main_list = (ListView) findViewById(R.id.lv_main_list);
//实例化进度条对话框
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("亲,正在玩命加载中哦!");
//实例化适配器
myAdapter = new MyAdapter();
//设置适配器
lv_main_list.setAdapter(myAdapter);
}
//自己写个适配器类
class MyAdapter extends BaseAdapter{
@Override
public int getCount() {
return personList.size();
}
@Override
public Object getItem(int i) {
return personList.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
LinearLayout layout=new LinearLayout(MainActivity.this);
layout.setOrientation(LinearLayout.HORIZONTAL);
TextView textViewPid=new TextView(MainActivity.this);
textViewPid.setText(personList.get(i).getPid() +"\t\t\t\t"+"");
TextView textViewPname=new TextView(MainActivity.this);
textViewPname.setText(personList.get(i).getPname()+"\t\t\t\t");
TextView textViewPage=new TextView(MainActivity.this);
textViewPage.setText(personList.get(i).getPage() +"\t\t\t\t"+ "");
layout.addView(textViewPid);
layout.addView(textViewPname);
layout.addView(textViewPage);
return layout;
}
}
//获取xml数据
public void getXML(View view) {
new MyTask().execute();
}
//通过异步任务类获取数据
class MyTask extends AsyncTask {
private Person person;
//准备执行
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
@Override
protected Object doInBackground(Object[] params) {
//获取网络路径
String path = "http://192.168.43.170:8080/S2SH/getXmlData.action";
//实例化URL
try {
URL url = new URL(path);
//获取连接对象
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//设置请求方式
httpURLConnection.setRequestMethod("GET");
//设置连接超时
httpURLConnection.setConnectTimeout(5000);
//获取响应码
int code = httpURLConnection.getResponseCode();
if (code == 200) {
//响应成功,获取服务器返回过来的数据
InputStream is = httpURLConnection.getInputStream();
//解析PULL SAX 基于事件驱动
XmlPullParser xpp=Xml.newPullParser();
try {
xpp.setInput(is,"UTF-8");
int type=xpp.getEventType();
while(type!=XmlPullParser.END_DOCUMENT){
switch (type) {
case XmlPullParser.START_TAG:
//获取开始标签的名字
String startTagName=xpp.getName();
if("person".equals(startTagName)){
person = new Person();
//获取name属性值
String pid=xpp.getAttributeValue(0);
person.setPid(Integer.parseInt(pid));
}else if("pname".equals(startTagName)){
//获取sex的文本值
String pname=xpp.nextText();
person.setPname(pname);
}else if("page".equals(startTagName)){
//获取sex的文本值
String page=xpp.nextText();
person.setPage(Integer.parseInt(page));
}
break;
case XmlPullParser.END_TAG:
//获取到结束标签的名字
String endTagName=xpp.getName();
if("person".equals(endTagName)){
personList.add(person);
}
break;
}
type=xpp.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return personList;
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
//通知适配器发生改变
myAdapter.notifyDataSetChanged();
//取消进度条对话框
progressDialog.cancel();
}
}
}
layout.xml代码:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.android_parsexml.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="获取XML数据"
android:onClick="getXML"
/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:id="@+id/lv_main_list"
>ListView>
RelativeLayout>
实体类代码:
package com.example.android_parsexml;
public class Person {
private int pid;
private String pname;
private int page;
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public Person() {
super();
}
public Person(String pname, int page) {
super();
this.pname = pname;
this.page = page;
}
@Override
public String toString() {
return "Person [pid=" + pid + ", pname=" + pname + ", page=" + page + "]";
}
}
mainfests 添加权限:
<uses-permission android:name="android.permission.INTERNET">uses-permission>