Android:解析服务器响应的XML和JSON(包括服务器SSM搭建)

安卓APP要实现很多功能(比如登录注册、发表评论等)时都必须要使用到网络数据交互。所以在学习了这部分内容后,就将其以拿一个对象为例整理出来。服务器用的是SSM(SpringMVC、Spring、MyBatis)集合框架,返回响应数据格式为两种xml、json,下面会两种格式都举例

准备环境
  • java IDE:Eclipse(服务器)
  • 数据库:Mysql
  • 构建工具:Maven
  • jdk:1.7以上
  • android IDE:AndroidStudio(客户端)
开发流程如下:
  1. 准备开发环境
  2. 利用SSM搭建服务器
  3. 服务器生成XML或者JSON
  4. 客户端获得链接读取数据
  5. 开始解析 XML:(DOM、SAX、PUll)、Json:(原生态JSONObject,Gson,Fast.json)
  6. 通过listview展示
读取数据流程

我们先搭建服务器

1、新建一个mavenProject :

Android:解析服务器响应的XML和JSON(包括服务器SSM搭建)_第1张图片

这边我在知道需要哪些依赖架包时,一次性直接添加 (pom.xml):

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0modelVersion>
  <groupId>com.zkinggroupId>
  <artifactId>XmlParserartifactId>
  <packaging>warpackaging>
  <version>0.0.1-SNAPSHOTversion>
  <name>XmlParser Maven Webappname>
  <url>http://maven.apache.orgurl>

  
    <properties>
        <spring.version>4.3.3.RELEASEspring.version>
    properties>

 <dependencies>

        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.2.5version>
        dependency>

        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.38version>
        dependency>



        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.8.1version>
            <scope>testscope>
        dependency>

        
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>javax.servlet-apiartifactId>
            <version>3.1.0version>
        dependency>

        
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>1.2.17version>
        dependency>

        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-coreartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-oxmartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-txartifactId>
            <version>${spring.version}version>
        dependency>


        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-aopartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-context-supportartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>${spring.version}version>
        dependency>

        
        <dependency>
            <groupId>com.mchangegroupId>
            <artifactId>c3p0artifactId>
            <version>0.9.2.1version>
        dependency>
        

        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>1.3.0version>
        dependency>

        
        <dependency>
            <groupId>jstlgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>


        
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
            <version>2.6.3version>
        dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-coreartifactId>
            <version>2.6.3version>
        dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-annotationsartifactId>
            <version>2.6.3version>
        dependency>

        

  dependencies>
  <build>
    <finalName>XmlParserfinalName>
  build>
project>

2、首先我们先把myBatis搭建成功 注(MyBatisconfig.xml可以省略)





  <configuration>
        
        
      
      

  configuration>

person.java实体类

package com.zking.entity;

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 Person() {
        super();
        // TODO Auto-generated constructor stub
    }
    public int getPage() {
        return page;
    }
    public void setPage(int page) {
        this.page = page;
    }
    public Person(int pid, String pname, int page) {
        super();
        this.pid = pid;
        this.pname = pname;
        this.page = page;
    }
    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 + "]";
    }

}

PersonDao接口:

package com.zking.dao;

import java.util.List;
import java.util.ArrayList;

import com.zking.entity.Person;

public interface PersonDao {

    public void addPerson(Person person);

    public List getPersons();
}

person映射xml:



  <mapper namespace="com.zking.dao.PersonDao">
      <insert id="addPerson" parameterType="com.zking.entity.Person" >
          insert into person values(null,#{pname},#{page}); 
      insert>
      <select id="getPersons" resultType="com.zking.entity.Person">
          select * from person
      select>
  mapper>

mybatis这边就可以先测试一下搭建成功没有,可以通过

SqlSessionFactoryBuilder().build(Resources.getResourceAsStream(“MyBatisConfig.xml”));拿到Session工厂,具体代码就不贴了


添加一个日志管理
log4j.properties

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

3、下面搭建spring框架:

这边先来一个数据连接的配置文件:

uname=root##用户名
upass=tiger##密码
driver_class=com.mysql.jdbc.Driver##mysql驱动类
url=jdbc:mysql://localhost:3306/test//连接url

initPoolSize=5//数据连接池初始最小5个
maxPoolSize=10//数据连接池最大10

applicationContext.xml如下:


<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">

    
    <context:property-placeholder location="classpath:db.properties"/>

    
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
       <property name="user" value="${uname}">property>
        <property name="password" value="${upass}">property>
        <property name="jdbcUrl" value="${url}">property>
        <property name="driverClass" value="${driver_class}">property>

        <property name="initialPoolSize" value="${initPoolSize}">property>
        <property name="maxPoolSize" value="${maxPoolSize}">property>
    bean>

    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        
        <property name="dataSource" ref="dataSource" >property>
        
        <property name="configLocation" value="classpath:MyBatisConfig.xml">property>
        
        <property name="mapperLocations" value="classpath:com/zking/entity/*.xml">property>
    bean>


    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.zking.dao">property>
    bean>
beans>

4、下面搭建SpringMVC

springMVC.xml 这里记得把注解驱动放进去,如果不加,则会报406的错


<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">


    
    <context:component-scan base-package="com.zking">context:component-scan>


    
    <mvc:annotation-driven>mvc:annotation-driven>

    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/">property>
        <property name="suffix" value=".jsp">property>
    bean>    
beans>

PersonContorller.java:

package com.zking.contorller;


import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zking.dao.PersonDao;
import com.zking.entity.Person;
import com.zking.entity.Teacher;

//声明为控制器类
@Controller
public class PersonContorller  {

    //拿到接口对象
    @Autowired
    PersonDao personDao;


    //XML
    @RequestMapping("/getPersons")
    public ModelAndView getPersons(){
        List mypersons= personDao.getPersons();
        ModelAndView andView=new ModelAndView();
        andView.addObject("mypersons",mypersons);
        andView.setViewName("success");
        return andView;
    }


    //Json格式
    @RequestMapping("/getPersonJson")
    @ResponseBody
    public Teacher getPersonsJson(){
       Teacher teacher= new Teacher();
       teacher.setSchool("天王盖地虎");
       teacher.setNumber(20);
       List mypersons= personDao.getPersons();
       teacher.setPersons(mypersons);
        return teacher;
    }   
}

5、访问数据

如果是XML格式的,我们需要生成xml文件:
success.jsp:

<%@ page language="java" contentType="text/xml; charset=UTF-8"pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%@page isELIgnored="false" %>
<persons>
        <c:forEach items="${mypersons}" var="hh">
          <person id="${hh.pid }" name="${hh.pname }">
            <age>${hh.page }age>
          person>
        c:forEach>
persons>

如果是Json格式的,就只需在Contorller方法上面加上注解@ResponseBody,返回你需要的对象就行了

最后在来一个页面测试一下数据访问

getperson.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title heretitle>
head>
<body>
        <a href="getPersons.action">获取xml数据a>
        <a href="getPersonJson.action">获取Json数据a>

body>
html>

最后web.xml配置如下:



<web-app>
  <display-name>Archetype Created Web Applicationdisplay-name>



    
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:applicationContext.xmlparam-value>
    context-param>

    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>



  
    <servlet>
        <servlet-name>springDispatcherServletservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:springMVC.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>

    
    <servlet-mapping>
        <servlet-name>springDispatcherServletservlet-name>
        <url-pattern>*.actionurl-pattern>
    servlet-mapping>
web-app>

6、到这里,服务器的框架搭完,我们只需要在客户端(应用程序)中去拿数据就可以了

下面在Android app中分为两种方式去拿数据,一种是解析json,一种是解析XML
(6.1)、首先我们先解析json:

package com.example.android30_jsonparser;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.example.android30_jsonparser.entity.Person;
import com.example.android30_jsonparser.entity.Teacher;
import com.example.android30_jsonparser.uitl.ItemTag;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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.List;

import static android.os.Build.VERSION_CODES.M;
import static com.alibaba.fastjson.JSON.parseObject;

public class MainActivity extends AppCompatActivity {

    private Teacher teacher;
    private View vHead;//头部
    private ListView lv_json;
    private MyAdpter myAdpter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv_json = (ListView) findViewById(R.id.lv_json);


    }



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

    class MyAdpter extends BaseAdapter{


        @Override
        public int getCount() {
            return teacher.getPersons().size();
        }

        @Override
        public Object getItem(int i) {
            return teacher.getPersons().get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            if(view==null){//优化对象的重用
                view= LayoutInflater.from(MainActivity.this).inflate(R.layout.item_listview,null);
                ItemTag itemTag=new ItemTag();
                itemTag.tv_pid= (TextView) view.findViewById(R.id.tv_item_listview_pid);
                itemTag.tv_pname= (TextView) view.findViewById(R.id.tv_item_listview_pname);
                itemTag.tv_page= (TextView) view.findViewById(R.id.tv_item_listview_page);
                view.setTag(itemTag);
            }
            ItemTag itemTag= (ItemTag) view.getTag();
            itemTag.tv_pid.setText(""+teacher.getPersons().get(i).getPid());
            itemTag.tv_pname.setText(teacher.getPersons().get(i).getPname());
            itemTag.tv_page.setText(""+teacher.getPersons().get(i).getPage());
            return view;
        }
    }



    class MyAsyncTask extends AsyncTask{
        @Override
        protected Object doInBackground(Object[] objects) {//耗时操作
            String path="http://193.168.2.212:8080/XmlParser/getPersonJson.action";
            try {
                //获取路径
                URL url=new URL(path);
                HttpURLConnection  huc= (HttpURLConnection) url.openConnection();
                huc.setRequestMethod("GET");
                huc.setConnectTimeout(5000);
                if(huc.getResponseCode()==200){
                    InputStream is= huc.getInputStream();
                    BufferedReader br=new BufferedReader(new InputStreamReader(is));
                    StringBuffer sb=new StringBuffer();
                    String str=null;
                    while ((str=br.readLine())!=null){
                        sb.append(str);
                    }
                    br.close();
                    is.close();
                    //原生态解析(JSONSObject,JSONArray)
//                    JSONObject jb=new JSONObject(sb.toString());
//                    String school=jb.getString("school");
//                    int number=jb.getInt("number");
//                    Log.i("test",school+"   "+number);
//                    JSONArray ja= jb.getJSONArray("persons");
//                    for (int i=0;i
//                       JSONObject jbPerson=  ja.getJSONObject(i);
//                        int pid= jbPerson.getInt("pid");
//                        String pname= jbPerson.getString("pname");
//                        int page= jbPerson.getInt("page");
//                        Log.i("test",pid+"  "+pname+"  "+page);
//                    }

                    //阿里巴巴json解析(导入架包以及引用架包)
                    teacher= JSON.parseObject(sb.toString(), Teacher.class);
//                    Log.i("test","alibaba:"+teacher.getSchool()+"  "+teacher.getNumber());
//                    for (Person person : teacher.getPersons()) {
//                        Log.i("test",""+person);
//                    }

                    //Gson(google自带  需要f4引用架包)
//                    Gson gson=new Gson();
//                    Teacher teacher= gson.fromJson(sb.toString(), Teacher.class);
//                    Log.i("test","google:"+teacher.getSchool()+"  "+teacher.getNumber());
//                        for (Person person : teacher.getPersons()) {
//                        Log.i("test",""+person);
//                    }

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


            return null;
        }


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

            vHead= View.inflate(MainActivity.this, R.layout.item_main, null);
            TextView iv_school= (TextView) vHead.findViewById(R.id.iv_school);
            TextView iv_number= (TextView) vHead.findViewById(R.id.iv_number);
            iv_school.setText(teacher.getSchool());
            iv_number.setText(""+teacher.getNumber());
            //      头布局放入listView中
            lv_json.addHeaderView(vHead);

            myAdpter = new MyAdpter();
            lv_json.setAdapter(myAdpter);
            myAdpter.notifyDataSetChanged();//通知适配器发生改变
        }
    } 
}

(6.2)、布局文件:
activity_main.xml


<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:orientation="vertical"
    tools:context="com.example.android30_jsonparser.MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="获取JSON"
        android:onClick="getJson"
        />


    <ListView
        android:layout_width="match_parent"
        android:id="@+id/lv_json"
        android:layout_height="wrap_content">
    ListView>

LinearLayout>

(6.3)、别忘了在清单文件加网络权限

 <uses-permission android:name="android.permission.INTERNET">uses-permission>

效果图
Android:解析服务器响应的XML和JSON(包括服务器SSM搭建)_第2张图片


下面是XMl解析方式
package com.example.android29_xmlparser;

import android.net.Uri;
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 com.example.android29_xmlparser.entity.Person;

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;

import static android.R.attr.x;
import static android.transition.Fade.IN;
import static android.util.Xml.newPullParser;

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private List persons=new ArrayList<>();
    private MyAdapter myAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.lv_xml);
        myAdapter = new MyAdapter();
        listView.setAdapter(myAdapter);

    }

    public void getxml(View view){
        new MyAsyncTask().execute();//执行异步任务
    }


    class  MyAdapter extends BaseAdapter{


        @Override
        public int getCount() {
            return persons.size();
        }

        @Override
        public Object getItem(int i) {
            return persons.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 textViewID=new TextView(MainActivity.this);
            textViewID.setText(""+persons.get(i).getPid());
            TextView textViewName=new TextView(MainActivity.this);
            textViewName.setText(persons.get(i).getPname());
            TextView textViewage=new TextView(MainActivity.this);
            textViewage.setText(""+persons.get(i).getPage());
            layout.addView(textViewID);
            layout.addView(textViewName);
            layout.addView(textViewage);
            return layout;
        }
    }


    class  MyAsyncTask extends AsyncTask{


        private Person person;

        @Override
        protected Object doInBackground(Object[] objects) {
            //确定网络路径
            String path="http://193.168.2.198:8080/XmlParser/getPersons.action";
            try {
                //实例化URL
                URL url=new URL(path);
                //获取连接对象
                HttpURLConnection huc= (HttpURLConnection) url.openConnection();
                // 设置请求方式
                huc.setRequestMethod("GET");
                //设置请求连接超时的时间(优化)
                huc.setConnectTimeout(5000);
                //获取响应状态码
                int code=huc.getResponseCode();
                if(code==200){
                  //获取从服务器返回过来的数据
                    InputStream is=huc.getInputStream();
//                    BufferedReader br=new BufferedReader(new InputStreamReader(is));
//                    String str=null;
//                    while ((str=br.readLine())!=null){
//                        Log.i("test",str);
//                    }
                    //获得pull解析
                    XmlPullParser xpp= Xml.newPullParser();
                    xpp.setInput(is,"utf-8");
                    //得到类型
                    int type=xpp.getEventType();
                    //如果不等于结束文档
                    while(type!=XmlPullParser.END_DOCUMENT){
                        switch (type){
                            case XmlPullParser.START_TAG:
                                //得到标签名
                                String tagName=xpp.getName();
                                if("person".equals(tagName)){
                                    person = new Person();
                                    person.setPid(Integer.parseInt(xpp.getAttributeValue(0)));
                                    person.setPname(xpp.getAttributeValue(1));
                                }
                                if("age".equals(tagName)){
                                    person.setPage(Integer.parseInt(xpp.nextText()));
                                }
                                break;
                            case XmlPullParser.END_TAG:
                                //获取到结束标签的名字
                                String endTagName=xpp.getName();
                                if("person".equals(endTagName)){
                                    persons.add(person);
                                }
                                break;
                        }
                        //重新给type赋值
                        type=xpp.next();
                    }




                }

            } 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);
            myAdapter.notifyDataSetChanged();
        }
    }
}

布局文件:


<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.android29_xmlparser.MainActivity">


    <Button
        android:layout_width="match_parent"
        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_xml"
        >ListView>


LinearLayout>

好了,请求以及解析代码上面都写的很详细了,其他的代码只是作一个展示作用。

你可能感兴趣的:(java,android,xml解析,json解析)