XML SAX解析

SAX是一種佔用內存少且解析速度快的解析器,它採用的是事件驅動,它不須要解析完整個文檔,而是按照內容順序,看文檔某個部分是否符合xml語法,若是符合就觸發相應的事件。所謂的事件就是些回調方法( callback),這些方法定義在ContentHandler中,下面是其主要方法:
口startDocument:當遇到文檔的時候就觸發這個事件調用這個方法能夠在其中作些預處理工做。
口startElement(Stning namespaceURI,String localName,String qName,Attributes atts):當遇開始標籤的時候就會觸發這個方法。
口endElement(String uri,String localName,String name):當遇到結束標籤時觸發這個事件,調用此方法能夠作些善後工做。
口characters(char[]ch,int start,int length):當遇到xml內容時觸發這個方法。java

 

Student.xmlandroid

<?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.java數組

package com.supermario.saxxml;

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

整個解析過程的關鍵就是使用StudentHandler來解析xml文本。解析過程會一次調用startDocument(),startElement(),character(),endElement()和endDocument()須要注意的是,preTAG這個變量是用來存儲當前節點名稱的,在endElement0中要記得把它置爲空,不然可能引發一些誤判斷。網絡

package com.supermario.saxxml;

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;  
    }   
}

main.xmlapp

<?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="SAX解析" />
    <ListView
        android:id="@+id/listView1" 
        android:layout_height="wrap_content" 
        android:layout_width="fill_parent" />  
</LinearLayout>

SAXXMLActivity.javaide

package com.supermario.saxxml;

import java.util.ArrayList;  
import java.util.Iterator;  
import java.util.List;  
import javax.xml.parsers.SAXParserFactory;  
import org.xml.sax.InputSource;  
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class SaxXMLActivity 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();
       //枚舉數組中的元素
       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>(SaxXMLActivity.this, android.R.layout.simple_list_item_1, list);  
      //爲listview綁定適配器
       listView.setAdapter(adapter);  
    }  
   
      
}  
  //解析xml文件
private List<Student> parserXMl()  
{  
    //實例化一個SAX解析工廠
    SAXParserFactory factory=SAXParserFactory.newInstance();  
    List<Student>students=null;   
    try {
    //獲取xml解析器
    XMLReader reader=factory.newSAXParser().getXMLReader();  
    students=new ArrayList<Student>();  
    reader.setContentHandler(new StudentHandler(students));  
    //解析Assets下的student.xml文件
    reader.parse(new InputSource(SaxXMLActivity.this.getResources().getAssets().open("student.xml"))); 
    } catch (Exception e) {  
    // TODO: handle exception   
    }
    return students;  
}  
}

運行結果:函數

PIC_20131119_124111_7AC

相關文章
相關標籤/搜索