XML PULL模型

student.xmljava

<?xml version="1.0" encoding="utf-8"?>   
<stundets>
    <student id="20120812115">
      <name>張三</name>
        <speciality>通訊工程</speciality> 
      <qq>843200157</qq> 
    </student>
    <student id="20120812116">
      <name>李四</name> 
      <speciality>網絡工程</speciality> 
      <qq>812256156</qq> 
    </student> 
    <student id="20120812117">
      <name>王五</name> 
      <speciality>軟件工程</speciality>
      <qq>812750158</qq>
    </student> 
</stundets>

student.javaandroid

package xom.supermario.pullxml;

public class Student {  
    long Id;  //用於存放id信息
    String Name;  //用於存放Name信息
    String Speciality;  //用於存放專業信息
    long QQ;      //用於存放QQ信息
    //帶參數構造函數,用於初始化類
    public Student(long id, String name, String speciality, long qQ) {  
        super();  
        Id = id;  
        Name = name;  
        Speciality = speciality;  
        QQ = qQ;  
    }  
    //不帶參數構造函數
    public Student() {  
        super();  
    }  
    //取得id
    public long getId() {  
        return Id;  
    } 
    //取得Name
    public String getName() {  
        return Name;  
    }  
    //取得QQ
    public long getQQ() {  
        return QQ;  
    }  
    //取得專業信息
    public String getSpeciality() {  
        return Speciality;  
    }  
    //設置id
    public void setId(long id) {  
        Id = id;  
    }  
    //設置姓名
    public void setName(String name) {  
        Name = name;  
    }  
    //設置QQ
    public void setQQ(long qQ) {  
        QQ = qQ;  
    }  
    //設置專業
    public void setSpeciality(String speciality) {  
        Speciality = speciality;  
    }  
    }

studentHandler.java數組

package xom.supermario.pullxml;

import java.util.List;   
import org.xml.sax.Attributes;  
import org.xml.sax.SAXException;  
import org.xml.sax.helpers.DefaultHandler;  
import android.util.Log;
  
public class StudentHandler extends DefaultHandler {  
    private String preTAG;    //用於存儲xml節點的名稱
    private List<Student> ListStudent;  
    private Student stu;  
    //無參數實例化類
    public StudentHandler() {  
        super();  
    }
    //帶參數實例化類
    public StudentHandler(List<Student> listStudent) {  
        super();  
        ListStudent = listStudent;  
    }
    //開始解析文檔
    public void startDocument() throws SAXException {  
        // TODO Auto-generated method stub   
    Log.i("------>", "文檔開始");  
        super.startDocument();  
    }
    //開始解析文檔的元素
    public void startElement(String uri, String localName, String qName,  
            Attributes attributes) throws SAXException {  
        Log.i("localName-------->", localName);  
        preTAG=localName;  //將當前元素的名稱保存到preTAG
        if ("student".equals(localName)) {  
            stu=new Student();  //實例化一個student類
            //將ID信息保存到stu中
            stu.setId(Long.parseLong(attributes.getValue(0)));  
              
        for (int i = 0; i < attributes.getLength(); i++) {    
            Log.i("attributes-------->",String.valueOf(stu.getId()));  
            }  
        }  
        //這句話記得要執行
        super.startElement(uri, localName, qName, attributes);  
    }  
  
    public void endDocument() throws SAXException {  
      
        Log.i("------>", "文檔結束");  
        super.endDocument();  
    }  
    public void endElement(String uri, String localName, String qName)  
            throws SAXException {  
        preTAG="";  
        if ("student".equals(localName)) {  
        ListStudent.add(stu);  
        Log.i("-------->", "一個元素解析完成");  
        }  
        super.endElement(uri, localName, qName);  
    }     
    //解析節點文本內容
    public void characters(char[] ch, int start, int length)  
        throws SAXException {  
      
        String str; 
        //找出元素中的「name」節點
       if ("name".equals(preTAG)) {  
           str=new String(ch,start,length);  
            stu.setName(str);  
            Log.i("name=", stu.getName());  
        //找出元素中的「speciality」節點
        }else if ("speciality".equals(preTAG)) {  
            str=new String(ch,start,length);  
            stu.setSpeciality(str);  
            Log.i("speciality=", stu.getSpeciality());
        //找出元素中的「qq」節點
        }else if ("qq".equals(preTAG)) {  
            str=new String(ch,start,length);  
            stu.setQQ(Long.parseLong((str)));  
            Log.i("QQ=", String.valueOf(stu.getQQ()));  
        } 
        super.characters(ch, start, length);  
    }                
    public List<Student> getListStudent() {  
        return ListStudent;  
    }

    public void setListStudent(List<Student> listStudent) {  
        ListStudent = listStudent;  
    }   
}

layout.xml網絡

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <Button
        android:id="@+id/btn1"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:text="PULL解析" />
    <ListView
        android:id="@+id/listView1" 
        android:layout_height="wrap_content" 
        android:layout_width="fill_parent" />  
</LinearLayout>

pullXMLActivity.javaapp

package xom.supermario.pullxml;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class PullXMLActivity extends Activity {
    //新建一個按鍵
    private Button button;  
    //新建一個列表
    private ListView listView;
    //新建一個數組列表用於存放字符串數組
    private ArrayList<String> list=new ArrayList<String>();  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main); 
        button=(Button)findViewById(R.id.btn1);  
        listView=(ListView) findViewById(R.id.listView1);
        //爲按鍵綁定監聽器
        button.setOnClickListener(new ButtonListener());  
    }  
    
    class ButtonListener implements OnClickListener{  
    
        @Override  
        public void onClick(View v) {  
          //將解析後的結果存儲到students中   
           List<Student> students=parserXMl();
        //    List<Student> students=null;
           //枚舉數組中的元素
           for (Iterator iterator = students.iterator(); iterator.hasNext();) {  
               Student student = (Student) iterator.next();  
               //將類的內容轉換成字符串,依次存儲到list中
               list.add(String.valueOf(student.getId())+" "+student.getName()+" "+student.getSpeciality()+" "+String.valueOf((student.getQQ())));  
        }  
           //新建一個適配器daapter用於給listview提供數據
           ArrayAdapter<String> adapter=new ArrayAdapter<String>(PullXMLActivity.this, android.R.layout.simple_list_item_1, list);  
          //爲listview綁定適配器
           listView.setAdapter(adapter);  
        }  
       
          
    }  
    
      //解析xml文件
    private List<Student> parserXMl()  
    {
        //初始化一個List<student>變量,用於將全部student成員
        List<Student> students=null;
        //初始化一個student變量,用於存儲每個節點的信息
        Student stu=null;
        try{
            //打開資源文件student.xml
            InputStream inputstream=PullXMLActivity.this.getResources().getAssets().open("student.xml");
            //建立XmlParser有兩種方式
            //方式一:使用工廠類XmlPullParserFactory
            XmlPullParserFactory pullFactory=XmlPullParserFactory.newInstance();
            XmlPullParser xmlPullParser=pullFactory.newPullParser();
            //方式二:使用Android提供的實用工具類android.util.Xml
            //XmlPullParser xmlPullParser=Xml.newPullParser();
            //設置輸入字節流爲inputstream,並設置編碼方式爲「UTF-8」
            xmlPullParser.setInput(inputstream, "UTF-8");
            //取得事件類型,用於開始解析時的判斷
            int eventType=xmlPullParser.getEventType();
            //循環遍歷整個文件直到解析完畢
            while(eventType != XmlPullParser.END_DOCUMENT)
            {
                /*打印log顯示事件類型
                *START_DOCUMENT:0
                *END_DOCUMENT:1
                *START_TAG:2
                *END_TAG:3
                *TEXT:4
                */
                Log.e("guojs--->event",eventType+"");
                //用於存儲節點名稱
                String localName=null;
                switch(eventType)
                {
                case XmlPullParser.START_DOCUMENT:
                    //碰到文檔開頭則實例化students變量,並打印log
                    students=new ArrayList<Student>();
                    Log.e("guojs","start document!");
                    break;
                case XmlPullParser.START_TAG:
                {
                    localName=xmlPullParser.getName();
                    if ("student".equals(xmlPullParser.getName())) {  
                        stu=new Student();  //實例化一個student類
                        //將ID信息保存到stu中
                        stu.setId(Long.parseLong(xmlPullParser.getAttributeValue(0)));  
                        Log.e("guojs",stu.getId()+"");
                    }
                    else if(stu != null)
                    {
                        //聲明一個變量用於存儲節點文本
                        String currentData=null;
                        if("name".equals(xmlPullParser.getName()))
                        {
                            /*注意這裏nextText()的使用:當前事件爲START_TAG,
                             * 若是接下去是文本,就會返回當前的文本內容;若是下一個事件是END_TAG
                             * 就會返回空字符串;不然拋出一個異常。
                             */
                            currentData=xmlPullParser.nextText();
                            //存儲」name「的信息
                            stu.setName(currentData);
                        }
                        else if("speciality".equals(xmlPullParser.getName()))
                        {
                            currentData=xmlPullParser.nextText();
                            //存儲專業信息
                            stu.setSpeciality(currentData);
                        }else if("qq".equals(xmlPullParser.getName()))
                        {
                            currentData=xmlPullParser.nextText();
                            //存儲QQ信息
                            stu.setQQ(Long.parseLong(currentData));
                        }
                    }
                }
                break;
                case XmlPullParser.END_TAG:
                {
                    localName=xmlPullParser.getName();
                    Log.e("guojs--end tag",localName);
                    if("student".equals(localName) && stu != null)
                    {
                        //將stu添加進students數組列表中
                        students.add(stu);
                        //設置stu爲空
                        stu = null;
                    }
                }
                break;
                default:
                    break;
                }
                //解析下一個事件
                eventType=xmlPullParser.next();
            }
        }catch(Exception e)
        {
            e.printStackTrace();
        }
        return students;
    }  
}
相關文章
相關標籤/搜索