SAX(Simple API for XML)提供了一種基於事件的處理思路,不需要裝載、遍歷整個XML文件,只要發現你所關心的標簽或數據,就可以隨時停止解析。
1. xml讀取代碼,繼承DefaultHandler(內含解析XML文檔中產生的各種類型的事件的空實現,只需重寫用到的事件即可)。
事件處理的順序:一般在 startDocument() 初始化工作,在 endDocument() 中收尾的處理工作;startElement() - characters() - endDocument() 是一個XML節點讀取的過程,startElement() 用來初始判斷,characters() 獲取節點的字符數據,endDocument() 將數據寫入數據結構。
- package mytest.xml;
-
- import org.xml.sax.Attributes;
- import org.xml.sax.SAXException;
- import org.xml.sax.helpers.DefaultHandler;
-
- public class XmlHandler extends DefaultHandler {
-
- private String _name = null, _address = null;
- private int _id = 0, _age = 0, _flag = 0;
-
- private String _str = "";
- public String getString() {
- return _str;
- }
-
- @Override
- // 開始處理文檔時觸發
- public void startDocument() throws SAXException {
- super.startDocument();
- }
-
- @Override
- // 開始處理元素時觸發
- public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
- if(localName.equalsIgnoreCase("Student"))
- {
- String tmp = attributes.getValue("id");
- if(tmp != null) _id = Integer.parseInt(tmp);
- }
- else if(localName.equalsIgnoreCase("name"))
- _flag = 1;
- else if(localName.equalsIgnoreCase("age"))
- _flag = 2;
- else if(localName.equalsIgnoreCase("address"))
- _flag = 3;
- }
-
- @Override
- // 處理元素字符內容時觸發
- public void characters(char[] ch, int start, int length) throws SAXException {
- String tmp = new String(ch, start, length);
- if(_flag == 1) _name = tmp;
- else if(_flag == 2) _age = Integer.parseInt(tmp);
- else if(_flag == 3) _address = tmp;
- _flag = 0;
- super.characters(ch, start, length);
- }
-
- @Override
- // 元素處理結束時觸發
- public void endElement(String uri, String localName, String name)
- throws SAXException {
- if(localName.equalsIgnoreCase("Student"))
- {
- this._str += this._name + "\n" + "Id: " + this._id + "\nAge: " + this._age +
- "\nAddress: " + this._address + "\n\n";
- }
- super.endElement(uri, localName, name);
- }
-
- @Override
- // 文檔處理結束時觸發
- public void endDocument() throws SAXException {
- super.endDocument();
- }
- }
2. 主activity
- package mytest.xml;
-
- import java.io.File;
- import javax.xml.parsers.SAXParser;
- import javax.xml.parsers.SAXParserFactory;
-
- import Android.app.Activity;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.TextView;
-
- public class TestActivity extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- Button btn = (Button)this.findViewById(R.id.xmlReadBtn);
- btn.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View args0) {
- TextView text = (TextView)findViewById(R.id.xmlPathEdit);
- String str = readXml(text.getText().toString());
- text = (TextView)findViewById(R.id.shownText);
- if(str != null)
- text.setText(str);
- }
- });
- }
-
- private String readXml(String filepath) {
- String str = null;
- File f = new File(filepath);
- if(f.exists())
- {
- SAXParserFactory factory = SAXParserFactory.newInstance();
- try {
- SAXParser sp = factory.newSAXParser();
- XmlHandler handler = new XmlHandler();
- sp.parse(f, handler);
- str = handler.getString();
- } catch(Exception e) {
- e.printStackTrace();
- }
- }
- return str;
- }
- }
3. 頁面代碼
- <?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"
- android:weightSum="1">
-
- <TextView android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Path:"
- android:textSize="8pt"
- android:gravity="left" />
-
- <LinearLayout android:layout_height="wrap_content"
- android:orientation="horizontal" android:layout_width="fill_parent">
-
- <EditText android:id="@+id/xmlPathEdit"
- android:layout_width="278dp"
- android:layout_height="wrap_content"/>
-
- <Button android:layout_height="40dp"
- android:text="OK"
- android:layout_width="wrap_content"
- android:id="@+id/xmlReadBtn" />
-
- </LinearLayout>
-
- <TextView android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:id="@+id/shownText"
- android:textSize="8pt"
- android:gravity="left"
- android:layout_weight="0.86"/>
-
- </LinearLayout>
4. 讀取的xml文件結構
- <?xml version="1.0" encoding="utf-8" standalone="yes"?>
- <Students count="2">
- <Student id="0">
- <name>Bill</name>
- <age>13</age>
- <address>ABCDEFG</address>
- </Student>
- <Student id="1">
- <name>Nancy</name>
- <age>17</age>
- <address>HIJKLMN</address>
- </Student>
- </Students>