Android 解析XML 之SAX


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

student.xml

  1. <?xml version="1.0" encoding="utf-8"?>    
  2. <stundets>  
  3.   <student id="2009081315">  
  4.     <name>饶伟</name>  
  5.     <speciality>计算机科学与技术</speciality>  
  6.     <qq>812200157</qq>  
  7.   </student>  
  8.   
  9.     <student id="2009081316">  
  10.     <name>小伟</name>  
  11.     <speciality>网络工程</speciality>  
  12.     <qq>812200156</qq>  
  13.   </student>  
  14.     <student id="2009081318">  
  15.     <name>伟哥</name>  
  16.     <speciality>软件工程</speciality>  
  17.     <qq>812200158</qq>  
  18.   </student>  
  19.   
  20. </stundets>  
Student.java
  1. public class Student {  
  2.   
  3.     long Id;  
  4.     String Name;  
  5.     String Speciality;  
  6.     long QQ;  
  7.       
  8.     public Student(long id, String name, String speciality, long qQ) {  
  9.         super();  
  10.         Id = id;  
  11.         Name = name;  
  12.         Speciality = speciality;  
  13.         QQ = qQ;  
  14.     }  
  15.   
  16.     public Student() {  
  17.         super();  
  18.     }  
  19.   
  20.       
  21.     public long getId() {  
  22.         return Id;  
  23.     }  
  24.   
  25.     public String getName() {  
  26.         return Name;  
  27.     }  
  28.   
  29.     public long getQQ() {  
  30.         return QQ;  
  31.     }  
  32.   
  33.     public String getSpeciality() {  
  34.         return Speciality;  
  35.     }  
  36.   
  37.     public void setId(long id) {  
  38.         Id = id;  
  39.     }  
  40.   
  41.     public void setName(String name) {  
  42.         Name = name;  
  43.     }  
  44.   
  45.     public void setQQ(long qQ) {  
  46.         QQ = qQ;  
  47.     }  
  48.   
  49.     public void setSpeciality(String speciality) {  
  50.         Speciality = speciality;  
  51.     }  
  52.   
  53. }  
StudentHandler.java
  1. package rw.Xml_SAX;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.xml.sax.Attributes;  
  6. import org.xml.sax.SAXException;  
  7. import org.xml.sax.helpers.DefaultHandler;  
  8.   
  9. import Android.util.Log;  
  10.   
  11. public class StudentHandler extends DefaultHandler {  
  12.   
  13.   
  14.     private String preTAG;    
  15.     private List<Student> ListStudent;  
  16.     private Student stu;  
  17.       
  18.     public StudentHandler() {  
  19.         super();  
  20.     }  
  21.   
  22.     public StudentHandler(List<Student> listStudent) {  
  23.         super();  
  24.         ListStudent = listStudent;  
  25.     }  
  26.   
  27.   
  28.     public void startDocument() throws SAXException {  
  29.         // TODO Auto-generated method stub   
  30.     Log.i("------>""文档开始");  
  31.         super.startDocument();  
  32.     }  
  33.   
  34.     public void startElement(String uri, String localName, String qName,  
  35.             Attributes attributes) throws SAXException {  
  36.   
  37.   
  38.         Log.i("localName-------->", localName);  
  39.         preTAG=localName;  
  40.         if ("student".equals(localName)) {  
  41.             stu=new Student();  
  42.             stu.setId(Long.parseLong(attributes.getValue(0)));  
  43.               
  44.         for (int i = 0; i < attributes.getLength(); i++) {  
  45.             //Log.i("attributes-------->", attributes.getValue(i));   
  46.             Log.i("attributes-------->",String.valueOf(stu.getId()));  
  47.         }  
  48.     }  
  49.         super.startElement(uri, localName, qName, attributes);  
  50.     }  
  51.   
  52.     public void endDocument() throws SAXException {  
  53.       
  54.         Log.i("------>""文档结束");  
  55.         super.endDocument();  
  56.     }  
  57.   
  58.     public void endElement(String uri, String localName, String qName)  
  59.             throws SAXException {  
  60.         preTAG="";  
  61.         if ("student".equals(localName)) {  
  62.         ListStudent.add(stu);  
  63.         Log.i("-------->""一个元素解析完成");  
  64.         }  
  65.         super.endElement(uri, localName, qName);  
  66.     }  
  67.       
  68.       
  69. public void characters(char[] ch, int start, int length)  
  70.         throws SAXException {  
  71.       
  72.         String dateString;  
  73.        if ("name".equals(preTAG)) {  
  74.             dateString=new String(ch,start,length);  
  75.             stu.setName(dateString);  
  76.             Log.i("name=", stu.getName());  
  77.         }else if ("speciality".equals(preTAG)) {  
  78.             dateString=new String(ch,start,length);  
  79.             stu.setSpeciality(dateString);  
  80.             Log.i("speciality=", stu.getSpeciality());  
  81.         }else if ("qq".equals(preTAG)) {  
  82.             dateString=new String(ch,start,length);  
  83.             stu.setQQ(Long.parseLong((dateString)));  
  84.             Log.i("QQ=", String.valueOf(stu.getQQ()));  
  85.         }  
  86.   
  87.         super.characters(ch, start, length);  
  88. }  
  89.   
  90.   
  91.   
  92.   
  93. public List<Student> getListStudent() {  
  94.     return ListStudent;  
  95. }  
  96.   
  97. public void setListStudent(List<Student> listStudent) {  
  98.     ListStudent = listStudent;  
  99. }  
  100.   
  101. }  
XML_Sax1Activity.java(唯一的一个activity)
  1. import java.util.ArrayList;  
  2. import java.util.Iterator;  
  3. import java.util.List;  
  4.   
  5. import javax.xml.parsers.SAXParserFactory;  
  6.   
  7. import org.xml.sax.InputSource;  
  8. import org.xml.sax.XMLReader;  
  9.   
  10.   
  11. import android.app.Activity;  
  12. import android.os.Bundle;  
  13. import android.util.Log;  
  14. import android.view.View;  
  15. import android.view.View.OnClickListener;  
  16. import android.widget.Adapter;  
  17. import android.widget.ArrayAdapter;  
  18. import android.widget.Button;  
  19. import android.widget.ListView;  
  20. import android.widget.TextView;  
  21.   
  22. public class XMl_Sax1Activity extends Activity {  
  23.       private Button button;  
  24.       private TextView textView;  
  25.       private ListView listView;  
  26.       private List<String> list=new ArrayList<String>();  
  27.     public void onCreate(Bundle savedInstanceState) {  
  28.         super.onCreate(savedInstanceState);  
  29.         setContentView(R.layout.main);  
  30.         button=(Button)findViewById(R.id.button1);  
  31.         textView=(TextView)findViewById(R.id.textView1);  
  32.         listView=(ListView) findViewById(R.id.listView1);  
  33.         //InputSource xMLResourceString=new InputSource(XMl_Sax1Activity.this.getResources().openRawResource(R.raw.student));   
  34.         button.setOnClickListener(new ButtonListener());  
  35.     }  
  36.   
  37.     class ButtonListener implements OnClickListener{  
  38.   
  39.         @Override  
  40.         public void onClick(View v) {  
  41.                  
  42.                List<Student> students=parserXMl();  
  43.                for (Iterator iterator = students.iterator(); iterator.hasNext();) {  
  44.                Student student = (Student) iterator.next();  
  45.                 list.add(String.valueOf(student.getId())+" "+student.getName()+" "+student.getSpeciality()+" "+String.valueOf((student.getQQ())));  
  46.             }  
  47.              
  48.                ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, list);  
  49.                listView.setAdapter(adapter);  
  50.         }  
  51.           
  52.     }  
  53.       
  54.   private List<Student> parserXMl()  
  55.   {  
  56.         SAXParserFactory factory=SAXParserFactory.newInstance();  
  57.         List<Student>students=null;  
  58.         Student student=null;  
  59.         try {  
  60.             XMLReader reader=factory.newSAXParser().getXMLReader();  
  61.             students=new ArrayList<Student>();  
  62.             reader.setContentHandler(new StudentHandler(students));  
  63.             reader.parse(new InputSource(XMl_Sax1Activity.this.getResources().openRawResource(R.raw.student)));  
  64.             for (Iterator iterator = students.iterator(); iterator.hasNext();) {  
  65.                  student = (Student) students.iterator();     
  66.             }  
  67.             students.add(student);  
  68.         } catch (Exception e) {  
  69.             // TODO: handle exception   
  70.         }  
  71.         return students;  
  72.   }  
  73. }  
布局文件main.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     >  
  7.   
  8. <Button android:text="SAX解析" android:id="@+id/button1" android:layout_height="wrap_content" android:layout_width="match_parent"></Button>  
  9. <TextView android:text="" android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>  
  10. <ListView android:layout_height="wrap_content" android:id="@+id/listView1" android:layout_width="match_parent"></ListView>  
  11. </LinearLayout>  
运行效果

相关内容