XML的三种解析方式

一. Dom
二 .PULL
三.SAX
首先在main 文件夹中建一个assets文件夹
用来放你要解析的xml文件

image.png

代码如下:
···
package com.example.lenovo.mytest02;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Xml;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
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 java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

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 {
Button bt1,bt2,bt3;
TextView tx;
InputStream is;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
public void init(){
bt1 = (Button) findViewById(R.id.button);
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
//要解析的xml
is= getAssets().open("users.xml");
tx.setText("Dom:\n"+ parseXmlDom(is)+"");
} catch (Exception e) {
e.printStackTrace();
}

        }


    });
    bt2 =(Button) findViewById(R.id.button2);
    bt2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                //要解析的xml
                is= getAssets().open("users.xml");
                tx.setText("PULL:\n"+ parseXMLPULL(is).toString());
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    });
    bt3 = (Button)findViewById(R.id.button3);
    bt3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                //要解析的xml
                is= getAssets().open("users.xml");
                tx.setText("SAX:\n"+  parseXMLBySAX(is).toString());
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    });
    tx = (TextView) findViewById(R.id.textView);


}
//DOM解析
public ArrayList> parseXmlDom(InputStream is) throws ParserConfigurationException {
    ArrayList>alist=new ArrayList<>();

    try {
        //创建工厂
        DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
        //创建Builder类对象
        DocumentBuilder db =dbf.newDocumentBuilder();
        //创建文本对象
        Document dom = db.parse(is);
        //获取解析文档中的所有节点信息
        Element root = dom.getDocumentElement();
        //提取需要解析的标签
        NodeList nodeList = root.getElementsByTagName("person");
        for (int i = 0; i  map = new HashMap<>();
            map.put("id", et.getAttribute("id"));
            //获取所有子节点
            NodeList childList = et.getChildNodes();
            for (int j = 0; j  map = null;
public ArrayList> parseXMLPULL(InputStream is) {
    ArrayList> alist = new ArrayList<>();
    //创建解析工具
    XmlPullParser pull = Xml.newPullParser();
    //加载数据源

    try {
        pull.setInput(is, "UTF-8");
        //边读边解析  文档开始 标签开始 标签结束  文档结束
        //获取解析数据的第一个标签
        int type = pull.getEventType();
        while (type != XmlPullParser.END_DOCUMENT) {
            switch (type) {
                case XmlPullParser.START_DOCUMENT://文档开始
                    break;
                case XmlPullParser.START_TAG://标签开始
                    if (pull.getName().equals("person")) {
                        map = new HashMap<>();
                        map.put("id", pull.getAttributeValue(0));
                    }
                    if (map != null) {
                        if (pull.getName().equals("name")) {
                            map.put("name", pull.nextText());
                        }
                        if (pull.getName().equals("age")) {
                            map.put("age", pull.nextText());
                        }
                    }
                    break;
                case XmlPullParser.END_TAG://标签结束
                    if (pull.getName().equals("person")) {
                        alist.add(map);
                    }
                    break;
            }
            //pull解析  解析完一个标签后不会自动指向下一个标签 需要手动指向
            pull.next();//指向下一个标签
            type = pull.getEventType();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }


    return  alist;
}

//SAX解析
public ArrayList> parseXMLBySAX(InputStream is) {
    try {
    //创建工厂类
    SAXParserFactory spf = SAXParserFactory.newInstance();
     //创建解析类
        SAXParser sax = spf.newSAXParser();
        //创建工具类
        MyHandler handler = new MyHandler();
        //解析工具和解析类结合
        sax.parse(is,handler);
        return handler.alist;

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;

}
//Sax解析需要单独创建解析的工具类  特点跟Pull一样 采用事件驱动(边读边解析)
//效率高,可以解析大文档  区别于Pull的是Sax不能停止
class MyHandler extends DefaultHandler {
    ArrayList> alist = new ArrayList<>();
    HashMap map = null;
    String tag = null;
    @Override//文档开始
    public void startDocument() throws SAXException {
    }
    @Override //解析开始标签  可以获取属性信息 不能获取正文信息
    //参数2  解析到的标签名称  参数4  获取的属性信息
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        if (localName.equals("person")) {
            map = new HashMap<>();
            map.put("id", attributes.getValue(0));
        }
        tag = localName;
    }
    @Override//获取开始标签对应的正文信息
    public void characters(char[] ch, int start, int length) throws SAXException {
        //转换数据
        String data = new String(ch,start,length);
        if(map!=null && tag !=null){

            if(tag.equals("name")){
                map.put("name",data);
            }
            if(tag.equals("age")){
                map.put("age",data);
            }
        }

    }

    @Override//标签结束
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if(localName.equals("person")){
            alist.add(map);
            map = null;
        }
        tag = null;
    }

    @Override//文档结束
    public void endDocument() throws SAXException {
    }

}

}

···

你可能感兴趣的:(XML的三种解析方式)