xml的解析分为是三种,包括:DOM ,SAX ,PULL, PULL解析类似于SAX,都是基于流的操作文件,然后根据节点事件回调开发者的处理程序,因此比较节约内存资源。 pull是android附带的一个解析器。
下面我就来做一个pull解析的demo。以eclipse作为服务器,让androidstudio来获取eclipse的数据。
第一步:我们首先在eclipse中生成xml:
小编用了SSH和SSM做测试,至于如何搭建框架,就不说了。先说SSH中的步骤,框架搭好后,建立一个类,里面写上你要的属性,配置好struts.xml,在写Action包的程序:
我这里就没有从数据库获取值了,直接循环了10个数据
public class StudentAction extends ActionSupport{
public String getxml() {
System.out.println("12323");
//查询数据,获取数据
List<Student> students=new ArrayList<Student>();
for (int i = 0; i < 10; i++) {
Student st=new Student("sara"+i, "女");
students.add(st);
}
//将对象保存到请求域中
ServletActionContext.getRequest().setAttribute("students", students);
return "dataResult";
}
jsp的页面:
<?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" %>
<students><c:forEach items="${students}" var="s">
<student name="${s.sname}">
<sex>${s.sex}</sex>
</student>
</c:forEach>
</students>
把jsp 的html文件改成xml文件,注意一二之间不要空格,因为空格的也会被解析到。
在贴出action类里面的代码
public String getxml() {
//查询数据,获取数据
List<Student> students=new ArrayList<Student>();
for (int i = 0; i < 10; i++) {
Student st=new Student("sara"+i, "女");
students.add(st);
}
//将对象保存到请求域中
ServletActionContext.getRequest().setAttribute("students", students);
return "dataResult";
}
服务器就搭建好了,最后让手机和电脑处于同一个局域网下,让手机去获取eclipse的这一串数据,能获取到就匹配成功了。
接下来就是androidStudio做网络操作了,代码里都有注释:
package com.example.mynetdata;
import android.app.ProgressDialog;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
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 com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
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 {
List<Student> students=new ArrayList<>();
private ListView lv_main_list;
private GoogleApiClient client;
private MyAdpter myAdpter;
private ProgressDialog progressDialog;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//实例化一个进度条的框
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("正在加载中");
lv_main_list = (ListView) findViewById(R.id.lv_main_list);
//实例化适配器
myAdpter = new MyAdpter();
//通知、设置
lv_main_list.setAdapter(myAdpter);
}
class MyAdpter extends BaseAdapter{
@Override
public int getCount() {
return students.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout linearLayout=new LinearLayout(MainActivity.this);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
TextView textViewname=new TextView(MainActivity.this);
textViewname.setText(students.get(position).getSname());
TextView textViewsex=new TextView(MainActivity.this);
textViewsex.setText(students.get(position).getSex());
textViewsex.setTextSize(20);
textViewname.setTextSize(20);
linearLayout.addView(textViewname);
linearLayout.addView(textViewsex);
return linearLayout;
}
}
public void getXML(View view) {
new Mytask().execute();
}
class Mytask extends AsyncTask {
private Student student;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
@Override
protected Object doInBackground(Object[] params) {
//获取网络数据xml
//01确定网络路劲
String path = "http://192.168.86.109:8080/SSM/getxml.action";
try{
//02实例化url
URL url = new URL(path);
//03获取连接
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
//04设置请求方式
connection.setRequestMethod("GET");
//05设置请求连接超时的时间(优化)
connection.setConnectTimeout(5000);
//06获取响应码,结果吗
int code= connection.getResponseCode();
if (code==200){
//获取服务器发过来的数据
InputStream is=connection.getInputStream();
//测试
//缓冲字符流
/* BufferedReader br=new BufferedReader(new InputStreamReader(is));
String str=null;
while((str=br.readLine())!=null){
Log.i("test",str);
}*/
//解析pull,基于事件驱动
XmlPullParser xmlPullParser= Xml.newPullParser();
try {
xmlPullParser.setInput(is,"UTF-8");
int type=xmlPullParser.getEventType();
while(type!=xmlPullParser.END_DOCUMENT){
switch (type){
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
//获取开始标签的名字
String startTagName=xmlPullParser.getName();
if ("student".equals(startTagName)){
student = new Student();
//获取name的属性值
String name=xmlPullParser.getAttributeValue(0);
Log.i("test",name);
student.setSname(name);
}else if ("sex".equals(startTagName)){
//获取sex的文本值
String sex= xmlPullParser.nextText();
Log.i("test",sex);
student.setSex(sex);
}
break;
case XmlPullParser.END_TAG:
//获取结束标签的名字
String endTagName=xmlPullParser.getName();
if ("student".equals(endTagName)){
students.add(student);
}
break;
}
type=xmlPullParser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
//通知适配器发生改变
myAdpter.notifyDataSetChanged();
progressDialog.cancel();
}
}
}
最后在到清单文件里加入网络的权限就可以了:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>