欢迎访问移动开发之家(rcyd.net),关注移动开发教程。移动开发之家  移动开发问答|  每日更新
页面位置 : > > > 内容正文

Android 解析XML 之SAX,android解析xmlsax

来源: 开发者 投稿于  被查看 45487 次 评论:183

Android 解析XML 之SAX,android解析xmlsax


SAX是一种占用内存少且解析速度快的解析器,它采用的是事件启动,它不需要解析完整个文档,而是按照内容顺序 看文档某个部分是否符合xml语法,如果符合就触发相应的事件,所谓的事件就是些回调方法(callback),这些方法 定义在ContentHandler中,下面是其主要方法:
startDocument:当遇到文档的时候就触发这个事件 调用这个方法 可以在其中做些预处理工作
startElement: (String namespaceURI,String localName,String qName,Attributes atts)当遇开始标签的时候就会触发这个方法。
endElement(String uri,String localName,String name):当遇到结束标签时触发这个事件,调用此法可以做些善后工作。
charachers(char [] ch,int start,int length):当遇到xml内容时触发这个方法,用new String(ch,start,length)可以接受内容。
首先在 res目录下新建一个raw文件夹,然后再里面么新建一个student.xml

1.student.xml

    <?xml version="1.0" encoding="utf-8"?>    
    <stundets>  
      <student id="2009081315">  
        <name>饶伟</name>  
        <speciality>计算机科学与技术</speciality>  
        <qq>812200157</qq>  
      </student>  
      
        <student id="2009081316">  
        <name>小伟</name>  
        <speciality>网络工程</speciality>  
        <qq>812200156</qq>  
      </student>  
        <student id="2009081318">  
        <name>伟哥</name>  
        <speciality>软件工程</speciality>  
        <qq>812200158</qq>  
      </student>  
      
    </stundets>  

2.Student.java

public class Student {  

long Id;  
String Name;  
String Speciality;  
long QQ;  
  
public Student(long id, String name, String speciality, long qQ) {  
    super();  
    Id = id;  
    Name = name;  
    Speciality = speciality;  
    QQ = qQ;  
}  

public Student() {  
    super();  
}  

  
public long getId() {  
    return Id;  
}  

public String getName() {  
    return Name;  
}  

public long getQQ() {  
    return QQ;  
}  

public String getSpeciality() {  
    return Speciality;  
}  

public void setId(long id) {  
    Id = id;  
}  

public void setName(String name) {  
    Name = name;  
}  

public void setQQ(long qQ) {  
    QQ = qQ;  
}  

public void setSpeciality(String speciality) {  
    Speciality = speciality;  
}  

}  

3.StudentHandler.java

    package rw.Xml_SAX;  
      
    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;    
        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;  
            if ("student".equals(localName)) {  
                stu=new Student();  
                stu.setId(Long.parseLong(attributes.getValue(0)));  
                  
            for (int i = 0; i < attributes.getLength(); i++) {  
                //Log.i("attributes-------->", attributes.getValue(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 dateString;  
           if ("name".equals(preTAG)) {  
                dateString=new String(ch,start,length);  
                stu.setName(dateString);  
                Log.i("name=", stu.getName());  
            }else if ("speciality".equals(preTAG)) {  
                dateString=new String(ch,start,length);  
                stu.setSpeciality(dateString);  
                Log.i("speciality=", stu.getSpeciality());  
            }else if ("qq".equals(preTAG)) {  
                dateString=new String(ch,start,length);  
                stu.setQQ(Long.parseLong((dateString)));  
                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;  
    }  
      
    }  

4.XMl_Sax1Activity.java

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.util.Log;  
import Android.view.View;  
import Android.view.View.OnClickListener;  
import Android.widget.Adapter;  
import Android.widget.ArrayAdapter;  
import Android.widget.Button;  
import Android.widget.ListView;  
import Android.widget.TextView;  

public class XMl_Sax1Activity extends Activity {  
  private Button button;  
  private TextView textView;  
  private ListView listView;  
  private List<String> list=new ArrayList<String>();  
public void onCreate(Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState);  
    setContentView(R.layout.main);  
    button=(Button)findViewById(R.id.button1);  
    textView=(TextView)findViewById(R.id.textView1);  
    listView=(ListView) findViewById(R.id.listView1);  
    //InputSource xMLResourceString=new InputSource(XMl_Sax1Activity.this.getResources().openRawResource(R.raw.student));   
    button.setOnClickListener(new ButtonListener());  
}  

class ButtonListener implements OnClickListener{  

    @Override  
    public void onClick(View v) {  
	     
	   List<Student> students=parserXMl();  
	   for (Iterator iterator = students.iterator(); iterator.hasNext();) {  
	   Student student = (Student) iterator.next();  
	    list.add(String.valueOf(student.getId())+" "+student.getName()+" "+student.getSpeciality()+" "+String.valueOf((student.getQQ())));  
	}  
	 
	   ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(), Android.R.layout.simple_list_item_1, list);  
	   listView.setAdapter(adapter);  
    }  
      
}  
  
private List<Student> parserXMl()  
{  
    SAXParserFactory factory=SAXParserFactory.newInstance();  
    List<Student>students=null;  
    Student student=null;  
    try {  
	XMLReader reader=factory.newSAXParser().getXMLReader();  
	students=new ArrayList<Student>();  
	reader.setContentHandler(new StudentHandler(students));  
	reader.parse(new InputSource(XMl_Sax1Activity.this.getResources().openRawResource(R.raw.student)));  
	for (Iterator iterator = students.iterator(); iterator.hasNext();) {  
	     student = (Student) students.iterator();     
	}  
	students.add(student);  
    } catch (Exception e) {  
	// TODO: handle exception   
    }  
    return students;  
}  
}  

5.布局文件main.xml

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

用户评论