XML解析详解

来源:互联网 发布:建筑设计软件图片 编辑:程序博客网 时间:2024/06/04 23:34
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

代码片段(5)

[代码] student.xml

01<?xmlversion="1.0"encoding="utf-8"?>   
02<stundets
03  <studentid="2009081315"
04    <name>饶伟</name
05    <speciality>计算机科学与技术</speciality
06    <qq>812200157</qq
07  </student
08   
09    <studentid="2009081316"
10    <name>小伟</name
11    <speciality>网络工程</speciality
12    <qq>812200156</qq
13  </student
14    <studentid="2009081318"
15    <name>伟哥</name
16    <speciality>软件工程</speciality
17    <qq>812200158</qq
18  </student
19   
20</stundets>

[代码] Student.java

01public classStudent { 
02 
03long Id; 
04String Name; 
05String Speciality; 
06long QQ; 
07   
08public Student(longid, String name, String speciality, longqQ) { 
09    super(); 
10    Id = id; 
11    Name = name; 
12    Speciality = speciality; 
13    QQ = qQ; 
14
15 
16public Student() { 
17    super(); 
18
19 
20   
21public longgetId() { 
22    returnId; 
23
24 
25public String getName() { 
26    returnName; 
27
28 
29public longgetQQ() { 
30    returnQQ; 
31
32 
33public String getSpeciality() { 
34    returnSpeciality; 
35
36 
37public voidsetId(long id) { 
38    Id = id; 
39
40 
41public voidsetName(String name) { 
42    Name = name; 
43
44 
45public voidsetQQ(long qQ) { 
46    QQ = qQ; 
47
48 
49public voidsetSpeciality(String speciality) { 
50    Speciality = speciality; 
51
52 
53}

[代码] StudentHandler.java

01package rw.Xml_SAX; 
02   
03import java.util.List; 
04   
05import org.xml.sax.Attributes; 
06import org.xml.sax.SAXException; 
07import org.xml.sax.helpers.DefaultHandler; 
08   
09import Android.util.Log; 
10   
11public classStudentHandler extends DefaultHandler { 
12   
13   
14    privateString preTAG;   
15    privateList<Student> ListStudent; 
16    privateStudent stu; 
17       
18    publicStudentHandler() { 
19        super(); 
20    
21   
22    publicStudentHandler(List<Student> listStudent) { 
23        super(); 
24        ListStudent = listStudent; 
25    
26   
27   
28    publicvoid startDocument() throwsSAXException { 
29        // TODO Auto-generated method stub  
30    Log.i("------>","文档开始"); 
31        super.startDocument(); 
32    
33   
34    publicvoid 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=newStudent(); 
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    publicvoid endDocument() throwsSAXException { 
53       
54        Log.i("------>","文档结束"); 
55        super.endDocument(); 
56    
57   
58    publicvoid endElement(String uri, String localName, String qName) 
59            throwsSAXException { 
60        preTAG=""
61        if("student".equals(localName)) { 
62        ListStudent.add(stu); 
63        Log.i("-------->","一个元素解析完成"); 
64        
65        super.endElement(uri, localName, qName); 
66    
67       
68       
69public voidcharacters(char[] ch,int start, intlength) 
70        throwsSAXException { 
71       
72        String dateString; 
73       if("name".equals(preTAG)) { 
74            dateString=newString(ch,start,length); 
75            stu.setName(dateString); 
76            Log.i("name=", stu.getName()); 
77        }elseif ("speciality".equals(preTAG)) { 
78            dateString=newString(ch,start,length); 
79            stu.setSpeciality(dateString); 
80            Log.i("speciality=", stu.getSpeciality()); 
81        }elseif ("qq".equals(preTAG)) { 
82            dateString=newString(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               
91public List<Student> getListStudent() { 
92    returnListStudent; 
93
94   
95public voidsetListStudent(List<Student> listStudent) { 
96    ListStudent = listStudent; 
97
98   
99}

[代码] XMl_Sax1Activity.java

01import java.util.ArrayList; 
02import java.util.Iterator; 
03import java.util.List; 
04 
05import javax.xml.parsers.SAXParserFactory; 
06 
07import org.xml.sax.InputSource; 
08import org.xml.sax.XMLReader; 
09 
10 
11import Android.app.Activity; 
12import Android.os.Bundle; 
13import Android.util.Log; 
14import Android.view.View; 
15import Android.view.View.OnClickListener; 
16import Android.widget.Adapter; 
17import Android.widget.ArrayAdapter; 
18import Android.widget.Button; 
19import Android.widget.ListView; 
20import Android.widget.TextView; 
21 
22public classXMl_Sax1Activity extends Activity { 
23  privateButton button; 
24  privateTextView textView; 
25  privateListView listView; 
26  privateList<String> list=new ArrayList<String>(); 
27public voidonCreate(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(newButtonListener()); 
35
36 
37class ButtonListenerimplements OnClickListener{ 
38 
39    @Override 
40    publicvoid 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=newArrayAdapter<String>(getApplicationContext(), Android.R.layout.simple_list_item_1, list); 
49       listView.setAdapter(adapter); 
50    
51       
52
53   
54private 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=newArrayList<Student>(); 
62    reader.setContentHandler(newStudentHandler(students)); 
63    reader.parse(newInputSource(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    returnstudents; 
72
73}

[代码] 布局文件main.xml

01<?xmlversion="1.0"encoding="utf-8"?> 
02<LinearLayoutxmlns:Android="http://schemas.android.com/apk/res/android" 
03    Android:orientation="vertical" 
04    Android:layout_width="fill_parent" 
05    Android:layout_height="fill_parent" 
06    
07   
08<ButtonAndroid:text="SAX解析"android:id="@+id/button1"android:layout_height="wrap_content"android:layout_width="match_parent"></Button
09<TextViewAndroid:text=""android:id="@+id/textView1"android:layout_width="wrap_content"android:layout_height="wrap_content"></TextView
10<ListViewAndroid:layout_height="wrap_content"android:id="@+id/listView1"android:layout_width="match_parent"></ListView
11</LinearLayout>