阳光网驿-企业信息化交流平台【DTC零售连锁全渠道解决方案】

 找回密码
 注册

QQ登录

只需一步,快速开始

扫描二维码登录本站

手机号码,快捷登录

老司机
查看: 1038|回复: 0

[转帖] Android 解析XML 之SAX

[复制链接]
  • TA的每日心情
    开心
    2012-3-7 10:15
  • 签到天数: 11 天

    [LV.3]偶尔看看II

    发表于 2012-1-4 12:01:00 | 显示全部楼层 |阅读模式
    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<?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>  
    [代码] Student.javapublic 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;  
    }  
    }  
    [代码] StudentHandler.javapackage 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;  
    }  
      
    }  
    [代码] XMl_Sax1Activity.javaimport 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;  
    }  
    }  
    [代码] 布局文件main.xml<?xml version="1.0" encoding="utf-8"?>  
    <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"  
        Androidrientation="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>  


    楼主热帖
    启用邀请码注册,提高发帖质量,建设交流社区
    您需要登录后才可以回帖 登录 | 注册

    本版积分规则

    快速回复 返回顶部 返回列表