30-31.Android-解析XML(PULL)-解析Json
程序员文章站
2024-01-12 19:58:52
...
一.知识概括
二.具体代码实现
代码图
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="获取网络XML数据"
android:onClick="getXMLByNet"
/><!--getXMLByNet:获取XML数据通过网络-->
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="获取网络Json数据"
android:onClick="getJsonByNet"
/>
</LinearLayout>
AndroidManifest.xml<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.zking.android30_parsexml">
<!--权限-->
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application android:allowBackup="true" android:icon="@mipmap/ic_launcher"
android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true" android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
1.解析XML(PULL)
在Tomcat\webapps\RooT里面手动建xml
students.xml
<?xml version="1.0" encoding="UTF-8"?>
<students>
<student sid="1">
<sname>名字1</sname>
<sage>年龄12</sage>
</student>
<student sid="2">
<sname>名字2</sname>
<sage>23</sage>
</student>
<student sid="3">
<sname>名字1</sname>
<sage>18</sage>
</student>
</students>
有可能乱码,所以要改编码方式
在浏览器查看网络环境是否已搭好
MainActivity.java
package com.zking.android30_parsexml;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void getXMLByNet(View view){//拿网络数据耗时,所以不能在主线程里面写
new MyTask().execute();
}
class MyTask extends AsyncTask{//异步任务类
//在此方法里面拿数据
@Override
protected Object doInBackground(Object[] params) {
//1.获取网络XML数据
String path="http://192.168.43.163:8080/students.xml";
try {
URL url=new URL(path);
HttpURLConnection connection= (HttpURLConnection) url.openConnection();//打开连接
//设置请求方式
connection.setRequestMethod("GET");
//设置请求超时的时间
connection.setConnectTimeout(5000);
//获取结果码
int code=connection.getResponseCode();
if(code==200){
//获取数据
InputStream is=connection.getInputStream();
// int len=0;
// byte[] buf=new byte[1024];
// StringBuffer stringBuffer=new StringBuffer();
// while((len=is.read(buf))!=-1){
// String s=new String(buf,0,len);
// stringBuffer.append(s);
// }
// Log.i("test",stringBuffer.toString());
//2.解析XML
XmlPullParser pullParser=Xml.newPullParser();
pullParser.setInput(is,"UTF-8");
//拿到解析的标签类型
int type=pullParser.getEventType();
while(type!=XmlPullParser.END_DOCUMENT){//如果不是解析文档,就一直解析
switch (type) {
case XmlPullParser.START_TAG://如果是开始标签
//获取开始标签的名字
String startTagName=pullParser.getName();
if("student".equals(startTagName)){//如果是student拿sid
//获取属性id的值
String sid=pullParser.getAttributeValue(0);//下标
Log.i("test",sid);
}else if("sname".equals(startTagName)){//如果是sname拿值
String sname=pullParser.nextText();//下一个文本
Log.i("test"," "+sname);
}else if("sage".equals(startTagName)){
String sage=pullParser.nextText();
Log.i("test"," "+sage);
}
break;
case XmlPullParser.END_TAG:
break;
}
//细节:
type=pullParser.next();//循环一次给下一个
}
is.close();//关闭流
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
return null;
}
//在此方法里面更新界面
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
}
}
}
效果图
2.解析Json
在Tomcat\webapps\RooT里面手动建xml
students.json
{"count":3,"students":[{"sid":1,"sname":"名字1","ssex":"女"},{"sid":2,"sname":"名字2","ssex":"人妖"},
{"sid":3,"sname":"名字3","ssex":"男"}]}
导jar包:fastjson-1.2.3.jar
MainActivity.java
package com.zking.android30_parsexml;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import com.alibaba.fastjson.JSON;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ProgressDialog pd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pd = new ProgressDialog(this);
pd.setMessage("正在拼命加载中....");
}
public void getXMLByNet(View view){//拿网络数据耗时,所以不能在主线程里面写
new MyTask().execute();
}
class MyTask extends AsyncTask{//异步任务类
//在此方法里面拿数据
@Override
protected Object doInBackground(Object[] params) {
//1.获取网络XML数据
String path="http://192.168.43.163:8080/students.xml";
try {
URL url=new URL(path);
HttpURLConnection connection= (HttpURLConnection) url.openConnection();//打开连接
//设置请求方式
connection.setRequestMethod("GET");
//设置请求超时的时间
connection.setConnectTimeout(5000);
//获取结果码
int code=connection.getResponseCode();
if(code==200){
//获取数据
InputStream is=connection.getInputStream();
// int len=0;
// byte[] buf=new byte[1024];
// StringBuffer stringBuffer=new StringBuffer();
// while((len=is.read(buf))!=-1){
// String s=new String(buf,0,len);
// stringBuffer.append(s);
// }
// Log.i("test",stringBuffer.toString());
//2.解析XML
XmlPullParser pullParser=Xml.newPullParser();
pullParser.setInput(is,"UTF-8");
//拿到解析的标签类型
int type=pullParser.getEventType();
while(type!=XmlPullParser.END_DOCUMENT){//如果不是解析文档,就一直解析
switch (type) {
case XmlPullParser.START_TAG://如果是开始标签
//获取开始标签的名字
String startTagName=pullParser.getName();
if("student".equals(startTagName)){//如果是student拿sid
//获取属性id的值
String sid=pullParser.getAttributeValue(0);//下标
Log.i("test",sid);
}else if("sname".equals(startTagName)){//如果是sname拿值
String sname=pullParser.nextText();//下一个文本
Log.i("test"," "+sname);
}else if("sage".equals(startTagName)){
String sage=pullParser.nextText();
Log.i("test"," "+sage);
}
break;
case XmlPullParser.END_TAG:
break;
}
//细节:
type=pullParser.next();//循环一次给下一个
}
is.close();//关闭流
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
return null;
}
//在此方法里面更新界面
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
}
}
//拿网络json
public void getJsonByNet(View view){
new MyJsonTask().execute();
}
class MyJsonTask extends AsyncTask{
@Override
protected void onPreExecute() {//在执行之前
super.onPreExecute();
pd.show();
}
@Override
protected Object doInBackground(Object[] params) {
//1.获取网络Json数据
String path="http://192.168.43.163:8080/students.json";
try {
URL url=new URL(path);
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
if(connection.getResponseCode()==200){
InputStream is=connection.getInputStream();
int len=0;
byte[] buf=new byte[1024];
StringBuffer stringBuffer=new StringBuffer();
while((len=is.read(buf))!=-1){
String s=new String(buf,0,len);
stringBuffer.append(s);
}
Log.i("test",stringBuffer.toString());
//2.解析JSON(两种方式:json/Gson FastJson)
BigObject bigObject=JSON.parseObject(stringBuffer.toString(),BigObject.class);//解析对象
int count=bigObject.getCount();
Log.i("test",count+" ");
List<Student> students=bigObject.getStudents();
for (Student student : students) {
Log.i("test",student.getSname()+" "+student.getSsex());
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Object o) {
pd.cancel();
super.onPostExecute(o);
}
}
}
BigObject.javapackage com.zking.android30_parsexml;
import java.util.List;
/**
* Created by Administrator on 2017/7/26 0026.
*/
public class BigObject {
private int count;//必须与Tomcat里面的保持一致
private List<Student> students;
public BigObject() {
}
public BigObject(int count, List<Student> students) {
this.count = count;
this.students = students;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
}
Student.javapackage com.zking.android30_parsexml;
/**
* Created by Administrator on 2017/7/26 0026.
*/
public class Student {
private int sid;
private String sname;
private String ssex;
public Student() {
}
public Student(int sid, String sname, String ssex) {
this.sid = sid;
this.sname = sname;
this.ssex = ssex;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSsex() {
return ssex;
}
public void setSsex(String ssex) {
this.ssex = ssex;
}
}
效果图