Android Sax方法读取xml文件


SAX(Simple API for XML)提供了一种基于事件的处理思路,不需要装载、遍历整个XML文件,只要发现你所关心的标签或数据,就可以随时停止解析。

1. xml读取代码,继承DefaultHandler(内含解析XML文档中产生的各种类型的事件的空实现,只需重写用到的事件即可)。
事件处理的顺序:一般在 startDocument() 初始化工作,在 endDocument() 中收尾的处理工作;startElement() - characters() - endDocument() 是一个XML节点读取的过程,startElement() 用来初始判断,characters() 获取节点的字符数据,endDocument() 将数据写入数据结构。
  1. package mytest.xml;  
  2.   
  3. import org.xml.sax.Attributes;  
  4. import org.xml.sax.SAXException;  
  5. import org.xml.sax.helpers.DefaultHandler;  
  6.   
  7. public class XmlHandler extends DefaultHandler {  
  8.       
  9.     private String _name = null, _address = null;  
  10.     private int _id = 0, _age = 0, _flag = 0;   
  11.       
  12.     private String _str = "";     
  13.     public String getString() {  
  14.         return _str;  
  15.     }  
  16.   
  17.     @Override  
  18.     // 开始处理文档时触发   
  19.     public void startDocument() throws SAXException {  
  20.         super.startDocument();  
  21.     }  
  22.           
  23.     @Override  
  24.     // 开始处理元素时触发   
  25.     public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {          
  26.         if(localName.equalsIgnoreCase("Student"))  
  27.         {  
  28.             String tmp = attributes.getValue("id");  
  29.             if(tmp != null)     _id = Integer.parseInt(tmp);  
  30.         }  
  31.         else if(localName.equalsIgnoreCase("name"))  
  32.             _flag = 1;  
  33.         else if(localName.equalsIgnoreCase("age"))  
  34.             _flag = 2;  
  35.         else if(localName.equalsIgnoreCase("address"))  
  36.             _flag = 3;  
  37.     }    
  38.       
  39.     @Override  
  40.     // 处理元素字符内容时触发   
  41.     public void characters(char[] ch, int start, int length) throws SAXException {  
  42.         String tmp = new String(ch, start, length);  
  43.         if(_flag == 1)      _name = tmp;  
  44.         else if(_flag == 2)     _age = Integer.parseInt(tmp);  
  45.         else if(_flag == 3)     _address = tmp;  
  46.         _flag = 0;  
  47.         super.characters(ch, start, length);  
  48.     }    
  49.             
  50.     @Override  
  51.     // 元素处理结束时触发   
  52.     public void endElement(String uri, String localName, String name)   
  53.             throws SAXException {  
  54.         if(localName.equalsIgnoreCase("Student"))  
  55.         {  
  56.             this._str += this._name + "\n" + "Id: " + this._id + "\nAge: " + this._age +   
  57.                 "\nAddress: " + this._address + "\n\n";  
  58.         }  
  59.         super.endElement(uri, localName, name);  
  60.     }   
  61.       
  62.     @Override  
  63.     // 文档处理结束时触发   
  64.     public void endDocument() throws SAXException {  
  65.         super.endDocument();  
  66.     }  
  67. }  
2. 主activity
  1. package mytest.xml;  
  2.   
  3. import java.io.File;  
  4. import javax.xml.parsers.SAXParser;  
  5. import javax.xml.parsers.SAXParserFactory;  
  6.   
  7. import Android.app.Activity;  
  8. import android.os.Bundle;  
  9. import android.view.View;  
  10. import android.view.View.OnClickListener;  
  11. import android.widget.Button;  
  12. import android.widget.TextView;  
  13.   
  14. public class TestActivity extends Activity {  
  15.     /** Called when the activity is first created. */  
  16.     @Override  
  17.     public void onCreate(Bundle savedInstanceState) {  
  18.         super.onCreate(savedInstanceState);  
  19.         setContentView(R.layout.main);  
  20.           
  21.         Button btn = (Button)this.findViewById(R.id.xmlReadBtn);  
  22.         btn.setOnClickListener(new OnClickListener() {  
  23.             @Override  
  24.             public void onClick(View args0) {  
  25.                 TextView text = (TextView)findViewById(R.id.xmlPathEdit);  
  26.                 String str = readXml(text.getText().toString());  
  27.                 text = (TextView)findViewById(R.id.shownText);  
  28.                 if(str != null)       
  29.                     text.setText(str);  
  30.             }  
  31.         });  
  32.     }  
  33.       
  34.     private String readXml(String filepath) {  
  35.         String str = null;  
  36.         File f = new File(filepath);  
  37.         if(f.exists())  
  38.         {  
  39.             SAXParserFactory factory = SAXParserFactory.newInstance();  
  40.             try {  
  41.                 SAXParser sp = factory.newSAXParser();  
  42.                 XmlHandler handler = new XmlHandler();  
  43.                 sp.parse(f, handler);  
  44.                 str = handler.getString();  
  45.             } catch(Exception e) {  
  46.                 e.printStackTrace();  
  47.             }  
  48.         }  
  49.         return str;  
  50.     }  
  51. }  
3. 页面代码
  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.               android:weightSum="1">  
  7.                 
  8.     <TextView android:layout_width="wrap_content"  
  9.               android:layout_height="wrap_content"  
  10.               android:text="Path:"  
  11.               android:textSize="8pt"  
  12.               android:gravity="left" />  
  13.                 
  14.     <LinearLayout android:layout_height="wrap_content"  
  15.                   android:orientation="horizontal" android:layout_width="fill_parent">  
  16.                 
  17.         <EditText android:id="@+id/xmlPathEdit"   
  18.                   android:layout_width="278dp"   
  19.                   android:layout_height="wrap_content"/>  
  20.                     
  21.         <Button android:layout_height="40dp"   
  22.                 android:text="OK"   
  23.                 android:layout_width="wrap_content"   
  24.                 android:id="@+id/xmlReadBtn" />  
  25.                     
  26.     </LinearLayout>  
  27.       
  28.     <TextView android:layout_width="fill_parent"   
  29.               android:layout_height="wrap_content"  
  30.               android:id="@+id/shownText"  
  31.               android:textSize="8pt"  
  32.               android:gravity="left"   
  33.               android:layout_weight="0.86"/>  
  34.                 
  35. </LinearLayout>  
4. 读取的xml文件结构
  1. <?xml version="1.0" encoding="utf-8" standalone="yes"?>  
  2. <Students count="2">  
  3.     <Student id="0">  
  4.         <name>Bill</name>  
  5.         <age>13</age>  
  6.         <address>ABCDEFG</address>  
  7.     </Student>  
  8.     <Student id="1">  
  9.         <name>Nancy</name>  
  10.         <age>17</age>  
  11.         <address>HIJKLMN</address>  
  12.     </Student>  
  13. </Students>  

相关内容