Android Dom和XmlPullParse解析XML文件

Android Dom和XmlPullParse解析XML文件

最近在在XML解析,测试了DOM和XmlPullParse两种模式解析XML,记录下来!

首先,创建在Sdcard里创建Xml文件,然后,建立两个按钮分别使用DOM、XmlPullParse来解析Xml文件,并且分别显示在TextView中.

废话少说,先上效果图:

Android Dom和XmlPullParse解析XML文件

1,XmlPullParse使用基础:

1.1获取XmlPullParse

1 XmlPullParserFactory factory =XmlPullParserFactory.newInstance();
2 XmlPullParser xmlPullParser =factory.newPullParser();

1.2 设置XmlPullParse解析器的输入

1   this.getClass().getClassLoader();
2   xmlPullParser.setInput(ClassLoader.getSystemResourceAsStream(BOOKS_PATH),"UTF-8");

1.3 解析XML文档数据.其主要工作就是调用XmlPullParser.next()获取数据,然后再调用XmlPullParser.getEventType()得到当前解析状态再做相应的处理

int eventType = parser.getEventType(); //返回的状态类型
if (eventType == XmlPullParser.START_DOCUMENT) //XML文档开始
if (eventType == XmlPullParser.START_TAG) //开始读取某个标签
if (eventType == XmlPullParser.END_TAG) //结束读取某个标签
//TEXT:Text内容
if (eventType == XmlPullParser.END_DOCUMENT) //XML文档结束

 

2.布局文件,三个Button,两个TextView,代码如下:

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

    <Button
        android:id="@+id/create_xml"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="创建XML文件"/>

    <Button
        android:id="@+id/dom_xml"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="DOM解析XML"/>

    <Button
        android:id="@+id/pull_xml"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="XmlPullParse解析XML"/>

    <TextView
        android:id="@+id/dom_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/colorAccent"
        android:textSize="18dip"/>

    <TextView
        android:id="@+id/pull_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/colorPrimary"
        android:textSize="18dip"/>

</LinearLayout>

3.主Activity:创建Xml文件,和Dom和XmlPullParse解析XMlL,代码如下:

package com.zwl.xmlparseproject;

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

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

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

public class MainActivity extends Activity implements View.OnClickListener {

    private static final String TAG = MainActivity.class.getSimpleName();
    private static final String BOOKS_PATH ="/sdcard/books.xml";  //创建books.xml文件路径
    private Button mCreateXml,mDomXml,mPullXml;
    private TextView mDemoText,mPullText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setupViews();
    }

    private void setupViews() {
        mCreateXml =findViewById(R.id.create_xml);
        mDomXml =findViewById(R.id.dom_xml);
        mPullXml =findViewById(R.id.pull_xml);
        mDemoText =findViewById(R.id.dom_text);
        mPullText =findViewById(R.id.pull_text);
        mCreateXml.setOnClickListener(this);
        mDomXml.setOnClickListener(this);
        mPullXml.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.create_xml:
                Log.d(TAG,"create_xml");
                createXml();
                break;
            case R.id.dom_xml:
                Log.d(TAG,"dom_xml");
                domParseXML();
                break;
            case R.id.pull_xml:
                Log.d(TAG,"pull_xml");
                xmlPullParseXML();
                break;
            default:
                break;
        }
    }

    //xmlPullParse解析Xml
    private void xmlPullParseXML() {
        String res="本结果通过XmlPullParse解析:"+"\n";
        try{
            XmlPullParserFactory factory =XmlPullParserFactory.newInstance();
            XmlPullParser xmlPullParser =factory.newPullParser();
            this.getClass().getClassLoader();
            xmlPullParser.setInput(ClassLoader.getSystemResourceAsStream(BOOKS_PATH),"UTF-8");
            int eventType =xmlPullParser.getEventType();
            try {
                while (eventType!=XmlPullParser.END_DOCUMENT){
                    String nodename =xmlPullParser.getName();
                    switch (eventType){
                        case XmlPullParser.START_TAG:
                            if ("bookname".equals(nodename)){
                                res += "书名:"+xmlPullParser.nextText()+"";
                            }else if ("bookauthor".equals(nodename)){
                                res +="作者:"+xmlPullParser.nextText()+"\n";
                            }
                            break;
                        default:
                            break;
                    }
                    eventType =xmlPullParser.next();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        }
        mPullText.setText(res);
        Toast.makeText(MainActivity.this, "XmlPullParser解析成功", Toast.LENGTH_SHORT).show();
    }

    //dom解析XML文件
    private void domParseXML() {
        File file=new File(BOOKS_PATH);
        DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
        DocumentBuilder db =null;
        try{
            db =dbf.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        Document document =null;
        try{
            document =db.parse(file);
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Element root =document.getDocumentElement();
        NodeList books =root.getElementsByTagName("book");
        String res ="本结果是通过dom解析的:"+"\n";
        for (int i=0 ; i<books.getLength();i++){
            Node book = books.item(i);
            Node bookname=((org.w3c.dom.Element) book).getElementsByTagName("bookname").item(0);
            Node bookauthor=((org.w3c.dom.Element) book).getElementsByTagName("bookauthor").item(0);
            res += "书名:"+bookname.getFirstChild().getNodeValue()+""+
                    "作者:"+bookauthor.getFirstChild().getNodeValue()+"\n";
        }
        mDemoText.setText(res);
        Toast.makeText(MainActivity.this, "解析成功", Toast.LENGTH_SHORT).show();
    }

    //创建XML文件
    private void createXml() {
        File file =new File(BOOKS_PATH);
        try{
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(MainActivity.this, "exception in createnewfile() method", Toast.LENGTH_SHORT).show();
        }
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream =new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(MainActivity.this, "can‘t create file fileoutputStream", Toast.LENGTH_SHORT).show();
        }
        XmlSerializer serializer = Xml.newSerializer();
        try {
            serializer.setOutput(fileOutputStream,"UTF-8");
            serializer.startDocument(null,true);
            serializer.startTag(null,"books");
            for (int i=0 ;i<3;i++){
                serializer.startTag(null,"book");
                serializer.startTag(null,"bookname");
                serializer.text("Android测试"+i);
                serializer.endTag(null,"bookname");
                serializer.startTag(null,"bookauthor");
                serializer.text("xiaoshu"+i);
                serializer.endTag(null,"bookauthor");
                serializer.endTag(null,"book");
            }
            serializer.endTag(null,"books");
            serializer.endDocument();
            serializer.flush();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Toast.makeText(MainActivity.this, "创建xml文件成功", Toast.LENGTH_SHORT).show();
    }
}

4. 由于我们在Sd卡上新建了文件,需要在AndroidManifest.xml里增加权限

1 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>   //内外置SD卡写权限

完毕,全部代码如上.

相关推荐