XML解析方式

Pull解析

package com.example.adapter;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Xml;
import android.view.Menu;

import com.example.kaoshi.R;

public class MyXmlPull extends Activity {

    private Person p;
    private List list;

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

        XmlPullParser parser = Xml.newPullParser();

        // 得到文件

        File file = new File(Environment.getExternalStorageDirectory(),
                "person.xml");

        // 输入流

        try {
            FileInputStream fis = new FileInputStream(file);

            parser.setInput(fis, "utf-8");

            // 得到事件的类型

            int eventType = parser.getEventType();

            while (eventType != parser.END_DOCUMENT) {
                // 得到节点的名字

                String name = parser.getName();

                switch (eventType) {
                case XmlPullParser.START_TAG:
                    if ("persons".equals(name)) {
                        list = new ArrayList();
                    } else if ("person".equals(name)) {
                        p = new Person();
                    } else if ("name".equals(name)) {
                        p.setName(parser.nextText());
                    } else if ("age".equals(name)) {
                        p.setAge(parser.nextText());
                    }
                    break;

                case XmlPullParser.END_TAG:
                    if ("person".equals(name)) {
                        list.add(p);

                        p = null;
                    }
                default:
                    break;
                }

                // 下一个事件类型是什么

                eventType = parser.next();
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }



}

SAX解析

package com.example.my_saxparse;

import java.io.InputStream;
import java.util.ArrayList;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;

import org.xml.sax.SAXException;

import org.xml.sax.helpers.DefaultHandler;

import com.bawi.bean.Person;


import android.os.Bundle;
import android.app.Activity;

import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {

    private ListView lv;
    private ArrayList list;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


       //找控件

        lv = (ListView) findViewById(R.id.lv);




    }

    //设置解析按钮监听
    public void saxParse(View v)
    {


        try {

            //获取xml文件的流对象
            InputStream xmlInput = getAssets().open("data.xml");
            //创建SAX解析工厂对象
            SAXParserFactory factory = SAXParserFactory.newInstance();
            //通过工厂对象获取一个解析器对象
            SAXParser parser = factory.newSAXParser();
            //创建一个继承了DefaultHandler类的一个子类
            MyHandler mh  = new MyHandler();
            //使用指定文件和mh进行解析                                     
            parser.parse(xmlInput, mh);


            //调用获取集合的方法,将流对象进行传递
            list = mh.getList();
            //为lv设置监听
            lv.setAdapter(new BaseAdapter() {

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                    View view = View.inflate(MainActivity.this,R.layout.item, null);
                    TextView tv_1 = (TextView) view.findViewById(R.id.name_tv);
                    TextView tv_2 = (TextView) view.findViewById(R.id.age_tv);
                    tv_1.setText("姓名是:"+list.get(position).getName());
                    tv_2.setText("年龄是:"+list.get(position).getAge());
                    return view;
                }

                @Override
                public long getItemId(int position) {
                    return 0;
                }

                @Override
                public Object getItem(int position) {
                    return null;
                }

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

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



    }
    class MyHandler extends DefaultHandler{
        private ArrayList list = null;
        private Person p = null;
        private String preTag=null;//作用是记录解析时的上一个节点名称

//      public  ArrayList getList(InputStream xmlIput) throws Exception
//      {   
//          //创建SAX解析工厂对象
//          SAXParserFactory factory = SAXParserFactory.newInstance();
//          //通过工厂对象获取一个解析器对象
//          SAXParser parser = factory.newSAXParser();
//          MyHandler mh = new MyHandler();
//          //使用指定文件和mh进行解析
//          parser.parse(xmlIput, mh);
//          return mh.getList();
//          
//      }

        public ArrayList getList()
        {
            return list;
        }

        @Override
        public void characters(char[] ch, int start, int length)
                throws SAXException {
            if(preTag!=null)
            {
                String content = new String(ch,start,length);
                if("name".equals(preTag))
                {
                    p.setName(content);
                }
                else if("age".equals(preTag))
                {
                    p.setAge(Integer.parseInt(content));
                }

            }
        }

        @Override
        public void endElement(String uri, String localName, String qName)
                throws SAXException {
            if("person".equals(qName))
            {
                list.add(p);
            }

            preTag=null;
        /**当解析结束时置为空。这里很重要,例如,当图中画3的位置结束后,会调用这个方法 
            ,如果这里不把preTag置为null,根据startElement(....)方法,preTag的值还是book,当文档顺序读到图 
            中标记4的位置时,会执行characters(char[] ch, int start, int length)这个方法,而characters(....)方 
            法判断preTag!=null,会执行if判断的代码,这样就会把空值赋值给book,这不是我们想要的。*/
        }

        @Override
        public void startDocument() throws SAXException {
            list=new ArrayList();

        }

        @Override
        public void startElement(String uri, String localName, String qName,
                Attributes attributes) throws SAXException {
            if("person".equals(qName))
            {
                p=new Person();
            }
            preTag=qName;


        }



    }


}

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