Android 解析XML(3种方法)

Android中的三种XML解析方式:

DOM (Android不推荐  因为会一次加载所有的文件)     
SAX  PULL (是边读边解析)

可以在云盘下载原代码:http://pan.baidu.com/s/1kVv5qRX


以下是个小demo: 效果图在下面:

首先要在服务端生成XML
–生成XML要在 Eclipse 里编写(用的是SSH框架)

–Jsp代码: getData.jsp

<%@ 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="/front/fqAction.xhtml">获取XML数据</a><br/>
    <a href="/front/JsonAction.xhtml">获取Json数据</a>
</body>
</html>

然后编写实体类:

package com.zking.entity;

public class FQ {

    private String name;
    private String content;
    private String time;
    public FQ() {
        super();
        // TODO Auto-generated constructor stub
    }

    public FQ(String name, String content, String time) {
        super();
        this.name = name;
        this.content = content;
        this.time = time;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public String getTime() {
        return time;
    }
    public void setTime(String time) {
        this.time = time;
    }
}

Action里新建一个FQAction.java:

package com.zking.action;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.opensymphony.xwork2.ActionSupport;
import com.zking.entity.FQ;

@Controller
public class FQAction  {
    @RequestMapping(value="/front/fqAction.xhtml")
    public String getXML(HttpServletRequest req) throws Exception {
        // 获取数据
        // 调用数据库查询数据,返回对象集合(....) 
        List<FQ> fqs = new ArrayList<FQ>();
        for (int i = 1; i <= 10; i++) {
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH);
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            fqs.add(new FQ("pull" + i, "今天心情很nice", year + "-" + month + "-" + day));
        }

        // 将对象集合存放到请求域中
        req.setAttribute("fqs", fqs);
        return "dataResult";
    }

    @RequestMapping(value="/front/JsonAction.xhtml")
    public String getJson(HttpServletRequest req) throws Exception {
        // 获取数据
        // 调用数据库查询数据,返回对象集合(....) 
        List<FQ> fqs = new ArrayList<FQ>();
        for (int i = 1; i <= 10; i++) {
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH);
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            fqs.add(new FQ("Json+pull" + i, "今天心情很nice", year + "-" + month + "-" + day));
        }
//          {}对象        JsonObject
//          []集合    JsonArray
            //将对象集合转换成Json
            JSONObject json=new JSONObject();
            json.put("clazz", "9990");
            json.put("lists", fqs.size());

            JSONArray jsona=new JSONArray();
            for (FQ fq : fqs) {
                JSONObject object=new JSONObject();
                object.put("name", fq.getName());
                object.put("content", fq.getContent());
                object.put("time", fq.getTime());
                jsona.add(object);
            }
            json.put("fqs", jsona);

        // 将对象集合存放到请求域中
        req.setAttribute("fqs", json.toString());
        return "dataResultJson";
    }

}

这里写图片描述

然后新建一个JSP 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"%><fqs><c:forEach items="${fqs}" var="fq">
            <fq name="${fq.name}">
                <content>${fq.content}</content>
                <time>${fq.time}</time>
            </fq>
    </c:forEach>
    </fqs>

编写完成可以运行下
效果如:
注: 这个路径 http://localhost:8090/front/fqAction.xhtmllocalhost要改成你的网络IP地址
这里写图片描述

接下来要获取网络XML数据 (在Android Studio里编写)

-首先要先在清单文件下配置网络权限

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

-然后编写XMLactivity_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.dzz.android29_parsexml.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="match_parent"
        android:id="@+id/lv_main"
        >
    </ListView>
</LinearLayout>

-然后获取网络数据 MainActivity

package com.dzz.android29_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.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

public class MainActivity extends AppCompatActivity {

    private ListView lv_main;
    private ProgressDialog progressDialog;
    private List<FQ> lists=new ArrayList<>();
    private MyAdapter myAdapter;

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

        //适配器
        myAdapter = new MyAdapter();
        lv_main.setAdapter(myAdapter);

        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在加载。。。");
    }
    //适配器
    class MyAdapter extends BaseAdapter{

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

        @Override
        public Object getItem(int i) {
            return lists.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_content= (TextView) view.findViewById(R.id.lv_a);
                itemTag.tv_name= (TextView) view.findViewById(R.id.lv_b);
                itemTag.tv_time= (TextView) view.findViewById(R.id.lv_c);
                view.setTag(itemTag);
            }
            ItemTag itemTag= (ItemTag) view.getTag();
            itemTag.tv_name.setText(lists.get(i).getName());
            itemTag.tv_content.setText(lists.get(i).getContent());
            itemTag.tv_time.setText(lists.get(i).getTime());

            return view;
        }
    }

    public void getXML(View view){
        new MyTask().execute();//执行
    }
    class MyTask extends AsyncTask{
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog.show();
        }
        @Override
        protected Object doInBackground(Object[] objects) {
            List<FQ> fqs=new ArrayList<>();
            //获取网络数据
            //1.定义获取网络的数据       
            //这个路径 http://localhost:8090/front/fqAction.xhtml 在 values 的 strings.xml 下
            //可以编写一个
            //<resources>
            //    <string name="app_name">Android29_ParseXML</string>
            //    <string name="server_name">http://172.20.10.3:8090</string>
            //</resources>
            //可以公用一个    如下:

            String path=getString(R.string.server_name)+"/front/fqAction.xhtml";

            try {
                //2.实例化Url
                URL url=new URL(path);
                //3.获取连接对象
                HttpURLConnection con= (HttpURLConnection) url.openConnection();
                //4.设置请求方式
                con.setRequestMethod("GET");
                //5.设置请求连接超时的时间
                con.setConnectTimeout(5000);
                //6.获取响应码
                int code=con.getResponseCode();
                if(code==200){
                    //7.获取返回过来的数据(XML)
                    InputStream is =con.getInputStream();
                    Log.i("test",is+"***");
                    //8.测试(删除--注释)
                    //缓冲字符流
                    String str=null;
//                  测试用的
//                    BufferedReader br=new BufferedReader(new InputStreamReader(is));
//                    while ((str=br.readLine())!=null){
//                        Log.i("test",str);
//                    }
                    //9.解析XML
                    //解析XML有的方法: DOM   SAX  PULL
                    //1. 使用DOM解析
                    try {
                        DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance();
                        DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder();
                        Document document=documentBuilder.parse(is); //流越大解析的越大    占用内存空间
                        //获取根标签
                        Element root=document.getDocumentElement();
                        NodeList nodeList=root.getElementsByTagName("fq");
                        for (int i = 0; i < nodeList.getLength(); i++) {
                            Element element= (Element) nodeList.item(i);
                            //获取属性name
                            String name=element.getAttribute("name");
                            //获取子标签<content><time>
                            Element elementContent= (Element) element.getElementsByTagName("content").item(0);
                            String content=elementContent.getTextContent();
                            Element elementTime= (Element) element.getElementsByTagName("time").item(0);
                            String time=elementTime.getTextContent();

                            Log.i("test",name+" "+content+" "+time);

                            FQ fq=new FQ(name,content,time);
                            fqs.add(fq);
                        }

                    } catch (ParserConfigurationException e) {
                        e.printStackTrace();
                    } catch (SAXException e) {
                        e.printStackTrace();
                    }

//                    2.使用SAX解析: 特点:边读边解析  基于事件(方法)驱动方式
//                    //开始文档  开始标签  结束标签 结束文档  文本
//                    try {
//                        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
//                        SAXParser saxParser = saxParserFactory.newSAXParser();
//                        saxParser.parse(is, new DefaultHandler() {    //开始解析
//                            @Override    //文档的开始
//                            public void startDocument() throws SAXException {
//                                super.startDocument();
//                            }
//                            @Override  //文档的结束
//                            public void endDocument() throws SAXException {
//                                super.endDocument();
//                            }
//                            @Override
//                            public void characters(char[] ch, int start, int length) throws SAXException {
//                                super.characters(ch, start, length);
//                                if("content".equals(currentTag)){
//                                    String content=new String(ch,start,length);
//                                    fq.setContent(content);
//                                }
//                                else if("time".equals(currentTag)){
//                                    String time=new String(ch,start,length);
//                                    fq.setTime(time);
//                                }
//                            }
//                            @Override   //结束标签
//                            public void endElement(String uri, String localName, String qName) throws SAXException {
//                                super.endElement(uri, localName, qName);
//                                //细节
//                                currentTag=null;
//                                if("fq".equals(localName)){
//                                    fqs.add(fq);
//                                }
//                            }
//                            @Override   //开始标签
//                            public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
//                                super.startElement(uri, localName, qName, attributes);
//                                currentTag=localName;
//                                if("fq".equals(localName)){
                                    实例化对象
//                                    fq = new FQ();
//                                    String name=attributes.getValue(0);
//                                    fq.setName(name);
//                                }
//                            }
//                        });
//                    } catch (ParserConfigurationException e) {
//                        e.printStackTrace();
//                    } catch (SAXException e) {
//                        e.printStackTrace();
//                    }

                    //3. PULL 解析
//                    try {
//                        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("fq".equals(startTagName)){
//                                        ffq = new FQ();
//                                        String name= xmlPullParser.getAttributeValue(0);
//                                        ffq.setName(name);
//                                    }
//                                    else if("content".equals(startTagName)){
//                                        String content=xmlPullParser.nextText();
//                                        ffq.setContent(content);
//                                    }
//                                    else if("time".equals(startTagName)){
//                                        String time=xmlPullParser.nextText();
//                                        ffq.setTime(time);
//                                    }
//                                    break;
//                                case XmlPullParser.END_TAG:
//                                    //获取结束标签的名字
//                                    String endTagName= xmlPullParser.getName();
//                                    if("fq".equals(endTagName)){
//                                        fqs.add(ffq);
//                                    }
//                                    break;
//                            }
//                            type=xmlPullParser.next();
//
//                        }
//
//                    } catch (XmlPullParserException e) {
//                        e.printStackTrace();
//                    }



                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return fqs;
        }
        @Override   //更新页面
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            List<FQ> fqs=(List<FQ>) o;
            lists.addAll(fqs);
            myAdapter.notifyDataSetChanged();  //通知适配器发生改变

            progressDialog.cancel();
        }
    }
}

-在Activity 里新建 实体类 是要有的

package com.dzz.android29_parsexml;

public class FQ {
    private String name;
    private String content;
    private String time;
    public FQ() {
        super();
    }
    public FQ(String name, String content, String time) {
        super();
        this.name = name;
        this.content = content;
        this.time = time;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public String getTime() {
        return time;
    }
    public void setTime(String time) {
        this.time = time;
    }
}

-在Activity 里新建一个 ItemTag

package com.dzz.android29_parsexml;
import android.widget.TextView;
/**
 * Created by 朝花偏不夕拾 on 2017/2/24.
 */

public class ItemTag {
    public TextView tv_name;
    public TextView tv_content;
    public TextView tv_time;
}

-还要新建一个布局文件 - item_listview.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/lv_a" />

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/lv_b"  />

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/lv_c" />
</LinearLayout>

然后是效果图:
这里写图片描述
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值