首页 > 代码库 > Android中序列化对象到XMl 和 XML反序列化为对象

Android中序列化对象到XMl 和 XML反序列化为对象

package com.example.xmloperation;import java.io.File;import java.io.FileOutputStream;import java.util.ArrayList;import java.util.List;import java.util.Random;import org.xmlpull.v1.XmlPullParser;import org.xmlpull.v1.XmlPullParserException;import org.xmlpull.v1.XmlSerializer;import android.annotation.SuppressLint;import android.os.Bundle;import android.os.Environment;import android.support.v7.app.ActionBarActivity;import android.util.Log;import android.util.Xml;import android.view.View;import android.widget.TextView;import android.widget.Toast;import com.example.bean.SmsInfo;public class MainActivity extends ActionBarActivity {        private TextView content;            private List<SmsInfo> smsInfos = new ArrayList<SmsInfo>();    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                content = (TextView)findViewById(R.id.tv);                //将对象进行序列话        //1: 我们可以采用模拟的方法, 利用StringBuilder进行拼装XMl文件, 不过该方法不够灵活, 处理起来比较麻烦,但是工具底层的实现基本也是实现的。    }            //2: 利用Android提供的Xml.Serializer 来进行序列化对象文XML    @SuppressLint("ShowToast")    public void serializer2XML(View view) {        //初始化短信        init();                        Log.i("MainActivity", " 开始序列化");        XmlSerializer serializer =  Xml.newSerializer();        File file = new File(Environment.getExternalStorageDirectory(), "smsinfo.xml");        FileOutputStream os;        try {            os = new FileOutputStream(file);            serializer.setOutput(os, "utf-8");                        serializer.startDocument("utf-8", true);            serializer.startTag(null, "smss");            for (SmsInfo info : smsInfos) {                serializer.startTag(null, "sms");                serializer.attribute(null, "id", info.getId()+"");                                serializer.startTag(null, "body");                serializer.text(info.getBody());                serializer.endTag(null, "body");                                serializer.startTag(null, "type");                serializer.text(info.getType()+"");                serializer.endTag(null, "type");                                serializer.startTag(null, "date");                serializer.text(info.getDate()+"");                serializer.endTag(null, "date");                                serializer.startTag(null, "address");                serializer.text(info.getAddress());                serializer.endTag(null, "address");                                serializer.endTag(null, "sms");            }            serializer.endTag(null, "smss");            serializer.endDocument();                        os.close();                        Toast.makeText(this, "序列化成功", 0).show();                     } catch (Exception e) {            e.printStackTrace();            Toast.makeText(this, "序列化失败", 0).show();         }    }        //利用Pull解析XMl    public void deserialize(View view) {                Log.i("MainActivity", " 开始反序列化");                XmlPullParser parser = Xml.newPullParser();        List<SmsInfo> mInfos = null;        SmsInfo info = null;                try {            parser.setInput(MainActivity.class.getClassLoader().getResourceAsStream("smsinfo.xml"), "utf-8");                        int type = parser.getEventType();                        while (type != XmlPullParser.END_DOCUMENT) {                System.out.println("type = " + type);                switch (type) {                    case XmlPullParser.START_TAG:                        if ("smss".equals(parser.getName())) {                            mInfos = new ArrayList<SmsInfo>();                        } else if ("sms".equals(parser.getName())) {                            info = new SmsInfo();                            info.setId(Integer.parseInt(parser.getAttributeValue(0)));                        } else if ("body".equals(parser.getName())) {                            info.setBody(parser.nextText());                        } else if ("type".equals(parser.getName())) {                            String temp = parser.nextText();                            //System.out.println("temp = " + temp);                            info.setType(Integer.parseInt(temp));                        } else if ("date".equals(parser.getName())){                            info.setDate(Long.parseLong(parser.nextText()));                        } else if ("address".equals(parser.getName())) {                            info.setAddress(parser.nextText());                        }                        break;                     case XmlPullParser.END_TAG:                        if ("sms".equals(parser.getName())) {                            mInfos.add(info);                            info = null;                        }                        break;                }                type = parser.next();            }        } catch (Exception e) {            e.printStackTrace();            Toast.makeText(this, "反序列化失败", 0).show(); ;        }                StringBuilder sb = new StringBuilder();        System.out.println(mInfos.size());        for (SmsInfo info1 : mInfos) {            //System.out.println("info  = " + info.getAddress());            sb.append(info1.toString() + "\n");        }        content.setText(sb.toString());                    }    private void init() {        Random random = new Random();        long address = 18766960000l;        for (int i = 0; i < 10; ++i) {            System.out.println("i = " + i);            SmsInfo smsInfo = new SmsInfo(System.currentTimeMillis(), random.nextInt(2) + 1, "短信内容" + i, ""+address + i, i);            smsInfos.add(smsInfo);        }    }}

 

 

中间遇的坑爹的是在反序列化的时候你的xml中间每个元素之间不要出现空格,空文本, 否则指针指向的下一个就是空文本了, 解析会出现错误。