AndroidXml解析的三种方式list的转换

前端之家收集整理的这篇文章主要介绍了AndroidXml解析的三种方式list的转换前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

后台获取数据为XMl格式,就找了很多资料学习了下,
参考链接 参考链接
感谢博主:CodeYourSister!

安卓解析XMl主要通过三种方式: DOM, SAX,PULL;三种方式
其中大文件解析最好不要用 :DOM解析(文件树放在内存中,太占内存,不推荐)
SAX和Pull是基于事件驱动的;其中SAX解析方式是边下载边解析占用内存较少

下面上代码:activity中代码

package com.btzh.myxmltest;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Attr;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
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.HashMap;
import java.util.List;

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

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView textView;
    private String httpStr = "http://10.27.7.162:8080/frame/lemeeting/getinforoom";
    private String httpStrtest = "https://mail.qq.com/cgi-bin/readmail?sid=344d6HuF5sEcSiJ6&mailid=ZC3331-E0L~tCfZQmW4DWU9gT9aT73&nocheckframe=true&t=attachpreviewer&select=1&selectfile=&seq=";
    ProgressDialog progressDialog;
    String Strhttp = "\n" +
            "<lemeeting> <user>user9</user> " +
            "<conf_room> <conf_id>329</conf_id> <conf_name>?????</conf_name> " +
            " <start_time>2017-03-31 09:48:12</start_time> " +
            " <end_time>2017-04-01 09:48:12</end_time> " +
            "<conf_password>202cb962ac59075b964b07152d234b70</conf_password> " +
            " <group_id>1</group_id> " +
            " <world_id>600122</world_id> </conf_room></lemeeting>";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView)findViewById(R.id.spyq_text);
        findViewById(R.id.spyq_list_btn).setOnClickListener(this);
        findViewById(R.id.spyq_DOM_btn).setOnClickListener(this);
        findViewById(R.id.spyq_SAX_btn).setOnClickListener(this);
        findViewById(R.id.spyq_Pull_btn).setOnClickListener(this);
        progressDialog = new ProgressDialog(this);
    }

    private void showProgressDialog(){
        if (null!=progressDialog){
            progressDialog.show();
        }
    }
    private void DismissProgressDialog(){
        if (null!=progressDialog){
            progressDialog.dismiss();
        }
    }
    //开启异步线程
    class Get_Result extends AsyncTask<String,Integer,String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            /* 设置进度条风格,风格为圆形,旋转的 */
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            /* 设置ProgressDialog 标题 */
            progressDialog.setTitle("提示");
            /* 设置ProgressDialog 提示信息 */
            progressDialog.setMessage("请稍后...");
            /* 设置ProgressDialog 的进度条是否不明确 */
            progressDialog.setIndeterminate(false);
            /* 设置ProgressDialog 是否可以按退回按键取消 */
            progressDialog.setCancelable(true);
            showProgressDialog();
        }

        @Override
        protected String doInBackground(String... params) {
            String getresult = http_get(httpStr);
            return getresult;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            DismissProgressDialog();
            //对异步获取的到Xml格式的数据进行解析
            saxParse(s);
        }
    }

    private void saxXmlParse(String XmlStr) {
        InputStream inputStream = null;
        try {
            inputStream = getResources().getAssets().open(XmlStr);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(inputStream == null)
            return;

        final StringBuffer stringBuffer = new StringBuffer();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        try {
            SAXParser saxParser = factory.newSAXParser();
            DefaultHandler defaultHandler = new DefaultHandler(){
                //开始解析文档,即开始解析XML根元素时调用方法
                @Override
                public void startDocument() throws SAXException {
                    Log.d("zyr","startDocument");
                    super.startDocument();
                }
                //开始解析每个元素时都会调用方法
                @Override
                public void startElement(String uri,String localName,String qName,Attributes attributes) throws SAXException {
                    Log.e("zyr","startElement " + qName);
                    super.startElement(uri,localName,qName,attributes);
                    stringBuffer.append("<" + qName);
                    if(attributes!=null){
                        for(int i=0;i<attributes.getLength();i++){
                            stringBuffer.append(" " + attributes.getQName(i) + "=" + attributes.getValue(i));
                        }
                    }
                    stringBuffer.append(">");
                }
                //解析到每个元素的内容时会调用方法
                @Override
                public void characters(char[] ch,int start,int length) throws SAXException {
                    Log.d("zyr","characters " + new String(ch,start,start+length));
                    super.characters(ch,length);
                    stringBuffer.append(new String(ch,start+length));
                }
                //每个元素结束的时候都会调用方法

                @Override
                public void endElement(String uri,String qName) throws SAXException {
                    Log.e("zyr","endElement " + qName);
                    super.endElement(uri,qName);
                    stringBuffer.append("</" + qName + ">");
                }
                //结束解析文档,即解析根元素结束标签调用方法
                @Override
                public void endDocument() throws SAXException {
                    Log.d("zyr","endDocument");
                    super.endDocument();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            textView.setText("");
                            textView.setText(stringBuffer.toString());
                        }
                    });
                }
            };
            saxParser.parse(inputStream,defaultHandler);

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

/*********************************SAX解析xml——start**********************************************/
    private String get_qName = "";
    private String get_value = "";
    String value = "";
    private void saxParse(String xmlStr) {
        if (xmlStr==null||"".equals(xmlStr))
            return;
        final List<HashMap<String,String>> dataLV = new ArrayList<HashMap<String,String>>();
        final HashMap<String,String> tem = new HashMap<String,String>();
        InputStream inputStream = new ByteArrayInputStream(xmlStr.getBytes());
        if(inputStream == null)
            return;
        SAXParserFactory factory = SAXParserFactory.newInstance();
        try {
            SAXParser saxParser = factory.newSAXParser();
            DefaultHandler defaultHandler = new DefaultHandler(){
                //开始解析文档,即开始解析XML根元素时调用方法
                @Override
                public void startDocument() throws SAXException {
                    Log.d("zyr",Attributes attributes) throws SAXException {
                    super.startElement(uri,attributes);
                }
                //解析到每个元素的内容时会调用方法
                @Override
                public void characters(char[] ch,int length) throws SAXException {
                    super.characters(ch,length);
                    value =  new String(ch,start+length);
                }
                //每个元素结束的时候都会调用方法
                @Override
                public void endElement(String uri,String qName) throws SAXException {
                    super.endElement(uri,qName);
                    get_qName = Return_qName(qName);
                    get_value = Return_qName(value);
                    if (null == get_value ||"".equals(get_value)||get_value.isEmpty()||get_value.length()<=0){

                    }else {
                        tem.put(get_qName,get_value);
                    }
                }
                //结束解析文档,即解析根元素结束标签调用方法
                @Override
                public void endDocument() throws SAXException {
                    Log.d("zyr","endDocument");
                    super.endDocument();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tem.put(get_qName,get_value);
                            dataLV.add(tem);
                            getRoom_values(dataLV);
                            System.out.println("----datalv"+dataLV);
                            textView.setText("");
                            for (int j = 0;j<dataLV.size();++j){
                                HashMap map = dataLV.get(j);
                                textView.setText("conf_id="+
                                        map.get("conf_id").toString()+"\n"+"conf_name="+map.get("conf_name").toString()+
                                        "\n"+"start_time="+map.get("start_time").toString()+"\n"+"end_time="+map.get("end_time").toString()+
                                        "\n"+"conf_password="+map.get("conf_password").toString()+"\n"+"group_id="+map.get("group_id").toString()+
                                        "\n"+"world_id="+map.get("world_id").toString());
                            }

                        }
                    });
                }
            };
            saxParser.parse(inputStream,defaultHandler);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //返回标签内容
    private String Return_qName(String qName){
// String Error = "error";
        if (qName!=null&&!"".equals(qName)){
            return qName;
        }else {
            return qName;
        }
    }

    private void getRoom_values(List<HashMap<String,String>> list){
        int getRoomId = -10;  //房间ID
        String getConfTime = ""; //接收邀请时间
        String getConfCode = ""; //会议室验证码
        String inviter  = ""; //邀请人
        String RoomName = ""; //房间主题名称
        int Mes_type = -11; //消息类型
        String result = "";//返回值类型
        String world_id = "";
        for (int i = 0;i<list.size();++i){
            HashMap map = list.get(i);
// result = map.get("result").toString();
            world_id = map.get("world_id").toString();
// if ("99".equals(result)){
// show_Toast("无人接听!");
// }else if ("1".equals(result)){
// show_Toast("没有人员在线!");
// }else if ("2".equals(result)){
// show_Toast("没有空闲人员!");
// }else if ("0".equals(result)){
// getRoomId = Integer.parseInt(map.get("conf_id").toString());
// getConfTime = map.get("start_time").toString();
// getConfCode = map.get("").toString();/**????????????**/
// inviter = map.get("user").toString();
// RoomName = map.get("conf_name").toString();
// Mes_type = Integer.parseInt(map.get("").toString()); /**????????????**/
// showDialog(getRoomId,getConfTime,getConfCode,inviter,RoomName,Mes_type);
// }else
            if ("600122".equals(world_id)){
// showDialog(getRoomId,Mes_type);

            }else {
                show_Toast("未知错误!");
            }
        }
    }
    //吐司显示
    private void show_Toast(String message){
        Toast.makeText(getApplicationContext(),message,Toast.LENGTH_SHORT).show();
    }

/***********************************SAX解析XMl——end***************************************/
/************************************DOM解析Xml——start************************************/
    /** * 使用递归解析一个XML文档 * */
    private void domParse(String domXml) {
        InputStream inputStream = null;
        try {
            inputStream = getResources().getAssets().open(domXml);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(inputStream == null)
            return;
        StringBuffer stringBuffer = new StringBuffer();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(inputStream);
            Element rootElement = document.getDocumentElement();//users
            stringBuffer.append(parseElement(rootElement));
            textView.setText("");
            textView.setText(stringBuffer.toString());
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private String parseElement(Element element) {
        StringBuffer stringBuffer = new StringBuffer();
        String tagName = element.getNodeName();
        stringBuffer.append("<" + tagName);
        // element元素的所有属性构成的NamedNodeMap对象,需要对其进行判断
        NamedNodeMap attributeMap = element.getAttributes();
        // 如果存在属性,则打印属性
        if (null != attributeMap) {
            for (int i = 0; i < attributeMap.getLength(); i++) {
                // 获得该元素的每一个属性
                Attr attr = (Attr) attributeMap.item(i);
                // 属性名和属性
                String attrName = attr.getName();
                String attrValue = attr.getValue();
                // 注意属性值需要加上引号,所以需要\转义
                stringBuffer.append(" " + attrName + "=\"" + attrValue + "\"");
            }
        }
        // 关闭标签
        stringBuffer.append(">");
        // 至此已经打印出了元素名和其属性
        // 下面开始考虑它的子元素
        NodeList children = element.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            // 获取每一个child
            Node node = children.item(i);
            // 获取节点类型
            short nodeType = node.getNodeType();
            if (nodeType == Node.ELEMENT_NODE) {
                // 如果是元素类型,则递归输出
                stringBuffer.append(parseElement((Element) node));
            } else if (nodeType == Node.TEXT_NODE) {
                // 如果是文本类型,则输出节点值,及文本内容
                stringBuffer.append(node.getNodeValue());
            } else if (nodeType == Node.COMMENT_NODE) {
                // 如果是注释,则输出注释
                stringBuffer.append("<!--");
                Comment comment = (Comment) node;
                // 注释内容
                String data = comment.getData();
                stringBuffer.append(data);
                stringBuffer.append("-->");
            }
        }
        // 所有内容处理完之后,输出关闭根节点
        stringBuffer.append("</" + tagName + ">");
        return stringBuffer.toString();
    }
    /*********************************DOM解析Xml——end****************************/
    /*********************************pull解析xml——start*************************/
    private void pullParse(String pullxml) {
        InputStream inputStream = null;
        try {
            inputStream = getResources().getAssets().open(pullxml);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(inputStream == null)
            return;

        StringBuffer stringBuffer = new StringBuffer();
        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser xmlPullParser = factory.newPullParser();
            xmlPullParser.setInput(inputStream,"UTF-8");
            int eventType = xmlPullParser.getEventType();
            while (eventType!= XmlPullParser.END_DOCUMENT){
                switch (eventType){
                    case XmlPullParser.START_DOCUMENT:
                        break;
                    case XmlPullParser.START_TAG:
                        stringBuffer.append("<" + xmlPullParser.getName());
                        for(int i=0;i<xmlPullParser.getAttributeCount();i++){
                            stringBuffer.append(" " + xmlPullParser.getAttributeName(i) + "=" + xmlPullParser.getAttributeValue(i));
                        }
                        stringBuffer.append(">");
                        break;
                    case XmlPullParser.TEXT:
                        stringBuffer.append(xmlPullParser.getText());
                        break;
                    case XmlPullParser.END_TAG:
                        stringBuffer.append("</" + xmlPullParser.getName() + ">");
                        break;
                    case XmlPullParser.END_DOCUMENT:
                        break;
                }
                eventType = xmlPullParser.next();
            }
            textView.setText("");
            textView.append(stringBuffer.toString());
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /*********************************pull解析xml——end*************************/
    //http的get方法获取后台数据
    private String http_get(String http_Url){
        String result = null;
        BufferedReader reader = null;
        HttpURLConnection connection = null;
            try {
                URL url = new URL(http_Url);
                connection = (HttpURLConnection)url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(6*1000);
                connection.setUseCaches(false);
                connection.setReadTimeout(6*1000);
                connection.connect();
                if (HttpURLConnection.HTTP_OK==connection.getResponseCode()){
                    InputStream inputStream  = connection.getInputStream();
                    reader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
                    StringBuilder builder = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        builder.append(line).append("\n");
                    }
                    result = builder.toString();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if (null!=connection)
                    connection.disconnect();
                if (null!=reader)
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
            }
       return result;
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.spyq_SAX_btn:
                //SAX解析
                saxXmlParse("MyTest.xml");
                break;
            case R.id.spyq_DOM_btn:
                //dom解析
                domParse("MyTestOne.xml");
                break;
            case R.id.spyq_Pull_btn:
                //Pull解析
                pullParse("Mypull.xml");
                break;
            case R.id.spyq_list_btn:
                //SAX解析本地Xml文件转List
// saxParse(Strhttp);
                //解析服务器获取内容
                new Get_Result().execute();
                break;
            default:
                break;
        }
    }
}

所有的代码都在里面了,而且注释非常详细, 千万记得网络权限,测试时一直报错,无语了很长时间,原来权限没写,好气

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

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:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.btzh.myxmltest.MainActivity">
    <ScrollView  android:layout_width="match_parent" android:layout_height="match_parent">
        <LinearLayout  android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
            <Button  android:id="@+id/spyq_SAX_btn" android:text="SAX解析Xml" android:layout_width="match_parent" android:layout_height="wrap_content" />
            <Button  android:id="@+id/spyq_DOM_btn" android:text="DOM解析Xml" android:layout_width="match_parent" android:layout_height="wrap_content" />
            <Button  android:id="@+id/spyq_Pull_btn" android:text="Pull解析Xml" android:layout_width="match_parent" android:layout_height="wrap_content" />
            <Button  android:id="@+id/spyq_list_btn" android:text="SaX解析转list" android:layout_width="match_parent" android:layout_height="wrap_content" />
            <TextView  android:textSize="18sp" android:id="@+id/spyq_text" android:layout_width="match_parent" android:layout_height="wrap_content" />

        </LinearLayout>
    </ScrollView>

</LinearLayout>

效果图(就上传两张吧):

DEMO地址在评论第一条(日了不知为啥,必须全部退出CSDN才能看到上传资源,刷新刷不出来,晕死!)

猜你在找的XML相关文章