时间:2020-10-13 10:07:07 | 栏目:Android代码 | 点击:次
Android解析XML展示到ListView运行后的效果图如下:
服务端的请求页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <a href="studentActiongetXML.action" rel="external nofollow" >获取XML数据</a><br/> </body> </html>
服务端返回结果的页面
<?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.name}"> <sex>${s.sex}</sex> </student> </c:forEach> </students>
服务端的Java代码
package com.zking.action; import java.util.ArrayList; import java.util.List; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; import com.zking.entity.Student; public class StudentAction extends ActionSupport{ public String getXML() throws Exception { //查询数据库,获取数据 List<Student> students=new ArrayList<>(); for (int i = 1; i <=20; i++) { Student student=new Student("小霜"+i, "女"); students.add(student); } //将对象集合保存到请求域中 ServletActionContext.getRequest().setAttribute("students", students); return "dataResult"; } }
服务端的配置文件(struts.xml)
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <package name="myPackage" extends="struts-default"> <action name="studentAction*" class="com.zking.action.StudentAction" method="{1}"> <result name="dataResult">/dataResult.jsp</result> </action> </package> </struts>
服务端的运行结果
Android (布局文件 activity_main.xml)
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" 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" android:orientation="vertical" tools:context="com.example.g150825_android29_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:id="@+id/lv_main_list" ></ListView> </LinearLayout>
Android(Java代码 MainActivity)
package com.example.g150825_android29_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 java.io.BufferedReader; 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> studentList=new ArrayList<>(); private ListView lv_main_list; private MyAdater myAdater; private ProgressDialog progressDialog; @Override protected void onCreate(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); //实例化适配器 //设置适配器 myAdater = new MyAdater(); lv_main_list.setAdapter(myAdater); } class MyAdater extends BaseAdapter{ @Override public int getCount() { return studentList.size(); } @Override public Object getItem(int i) { return studentList.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View view, ViewGroup viewGroup) { LinearLayout linearLayout=new LinearLayout(MainActivity.this); linearLayout.setOrientation(LinearLayout.HORIZONTAL); TextView textViewName=new TextView(MainActivity.this); textViewName.setText(studentList.get(i).getName()); TextView textViewSex=new TextView(MainActivity.this); textViewSex.setText(studentList.get(i).getSex()); 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[] objects) { //01.确定网络数据 String path="http://192.168.43.152:8080/G150825_S2SH/studentActiongetXML.action"; try { //02.实例化URL URL url=new URL(path); //03.获取连接对象 HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection(); //04.设置请求方式 httpURLConnection.setRequestMethod("GET"); //05.设置请求连接超时的时间(优化) httpURLConnection.setConnectTimeout(5000); //06.获取响应码(结果码) int code=httpURLConnection.getResponseCode(); if (code==200){ //07.获取服务器返回过来的数据 InputStream is=httpURLConnection.getInputStream(); //测试(打印) //缓冲字符流 // BufferedReader br=new BufferedReader(new InputStreamReader(is)); // String str=null; // while ((str=br.readLine())!=null){ // Log.i("test",str); // } //解析XML(PULL) XmlPullParser xmlPullParser=Xml.newPullParser(); xmlPullParser.setInput(is,"UTF-8"); int type=xmlPullParser.getEventType(); while (type!=XmlPullParser.END_DOCUMENT){ switch (type){ case XmlPullParser.START_TAG: //获取开始标签 String startTagName=xmlPullParser.getName(); if ("student".equals(startTagName)){ student = new Student(); //获取name属性值 String name=xmlPullParser.getAttributeValue(0); student.setName(name); }else if("sex".equals(startTagName)){ //获取sex的文本值 String sex=xmlPullParser.nextText(); student.setSex(sex); } break; case XmlPullParser.END_TAG: //获取到结束标签的名字 String endTagName=xmlPullParser.getName(); if("student".equals(endTagName)){ studentList.add(student); } break; } type=xmlPullParser.next(); } } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Object o) { super.onPostExecute(o); //通知适配器发生改变 myAdater.notifyDataSetChanged(); progressDialog.cancel(); } } }
Android (实体类 Student)
package com.example.g150825_android29_parsexml; public class Student { private String name; private String sex; public Student() { super(); // TODO Auto-generated constructor stub } public Student(String name, String sex) { super(); this.name = name; this.sex = sex; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
在清单文件中添加权限即可(AndroidManifest.xml)
<!--添加网络权限--> <uses-permission android:name="android.permission.INTERNET"></uses-permission>