parseXML 与 parseJson

苏志
2023-12-01

1.解析网络数据:在tomcat的root下,分别写xml文件,json文件。注意编码格式,改为UTF-8;

<?xml version="1.0" encoding="UTF-8"?>
<student>
	<stu sid="1">
		<sname>1</sname>
		<sage>19</sage>
		<ssex>女</ssex>
	</stu>
	<stu sid="2">
		<sname>2</sname>
		<sage>19</sage>
		<ssex>男</ssex>
	</stu>
	<stu sid="3">
		<sname>3</sname>
		<sage>19</sage>
		<ssex>男</ssex>
	</stu>
</student>
json:

{"count":3,"students":[{"sid":1,"sname":"1"},{"sid":2,"sname":"2"},{"sid":3,"sname":"3"}]}



<?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"
    tools:context="com.zking.parsexml.MainActivity">

   <Button
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="获取xml的数据"
       android:onClick="getXML"/>


   <Button
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="获取json的数据"
       android:onClick="getJson"/>


</LinearLayout>

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.zking.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>

package com.zking.parsexml;

import java.util.List;

/**
 * Created by Administrator on 2017/7/26 0026.
 */

public class Out {
    private int count;
    private List<Students> students;

    public Out() {
    }

    public Out(int count, List<Students> students) {
        this.count = count;
        this.students = students;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public List<Students> getStudents() {
        return students;
    }

    public void setStudents(List<Students> students) {
        this.students = students;
    }
}

package com.zking.parsexml;

/**
 * Created by Administrator on 2017/7/26 0026.
 */

public class Students {
    private int sid;
    private String sname;

    public Students() {
    }

    public Students(int sid, String sname) {
        this.sid = sid;
        this.sname = sname;
    }

    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;
    }
}

package com.zking.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 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 getXML(View view){
        new MyGetXML().execute();
    }

    class MyGetXML extends AsyncTask{

        @Override
        protected Object doInBackground(Object[] params) {
            //在后台运行数据
            //获取访问网络数据路径
            String path="http://192.168.43.22:8080/student.xml";
            //加载路径
            try {
                URL url=new URL(path);
                //打开网址
                HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
                //设置请求方式
                httpURLConnection.setRequestMethod("GET");
                //设置请求时间(获取数据)
                httpURLConnection.setConnectTimeout(5000);
                //获取响应码
                int a=httpURLConnection.getResponseCode();
                if(a==200){
                    //获取数据--以流的方式
                    InputStream is = httpURLConnection.getInputStream();
                   /* int len=0;
                    byte[]b=new byte[1024];
                    StringBuffer sb=new StringBuffer();
                    while ((len= is.read(b))!=-1){
                        String s=new String(b,0,len);
                        sb.append(s);
                    }*/
                    //解析XML
                    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 start=xmlPullParser.getName();
                                if("stu".equals(start)){
                                    String sid= xmlPullParser.getAttributeValue(0);
                                    Log.i("test",sid);
                                }else if("sname".equals(start)){
                                  String sname= xmlPullParser.nextText();
                                    Log.i("test",sname);
                                }else if("sage".equals(start)){
                                   String sage= xmlPullParser.nextText();
                                    Log.i("test",sage);
                                }else if("ssex".equals(start)){
                                    String ssex=xmlPullParser.nextText();
                                    Log.i("test",ssex);
                                }
                                break;
                            case XmlPullParser.END_TAG:
                                break;
                        }
                        type=xmlPullParser.next();
                    }
                   // Log.i("test",sb.toString());
                    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);
        }
    }


    public void getJson(View view){
        new MyGetJson().execute();
    }

    class  MyGetJson extends AsyncTask{
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd.show();

        }

        @Override
        protected Object doInBackground(Object[] params) {
            //获取网络路径
            String path="http://192.168.43.22:8080/students.json";
            //加载网络路径
            try {
                URL url=new URL(path);
                HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
                //设置请求方式
                httpURLConnection.setRequestMethod("GET");
                //设置加载数据的时间
                httpURLConnection.setConnectTimeout(5000);
                if(httpURLConnection.getResponseCode()==200){
                    InputStream is=httpURLConnection.getInputStream();
                    int len=0;
                    byte[]b=new byte[1024];
                    StringBuffer sb=new StringBuffer();
                    while((len=is.read(b))!=-1){
                        String s=new String(b,0,len);
                        sb.append(s);
                    }
                    Log.i("test",sb.toString());
                    //解析json
                    Out out=JSON.parseObject(sb.toString(),Out.class);
                    int count=out.getCount();
                    List<Students> students=out.getStudents();
                    for (Students s : students) {
                        Log.i("test",s.getSid()+"  "+s.getSname());
                    }

                    is.close();

                }


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            pd.cancel();
        }
    }




}




 类似资料: