編輯:關於 Android 開發
SAX(Simple API for XML)是一款解析速度快、內存佔用低的 XML 解析器,非常契合 Android 這類資源受限的設備。
SAX 屬於事件驅動的流式解析:從文檔開頭順序讀到結尾,中途既不能暫停也不能回退。它的核心是一套事件處理模型,圍繞「事件源」與「事件處理器」協作——事件源產生事件,事件處理器響應事件。事件源在調用處理器的特定方法時,還會把當前事件的上下文信息一併傳入,處理器據此決定自己的行为。
值得一提的是,SAX 並不需要把整份文檔載入內存。它按文檔順序逐段讀取,判斷當前讀到的字符是否構成合法 XML 語法的一部分,一旦成立就觸發對應事件。所謂「事件」,本質上就是一組定義在 ContentHandler 接口中的回調方法。
在 SAX 體系裡,事件源是 org.xml.sax 包的 XMLReader,它通過 parse() 方法解析文檔並產生事件;事件處理器則是 ContentHandler、DTDHandler、ErrorHandler、EntityResolver 這四個接口,XMLReader 通過 setXXX() 系列的註冊方法與它們建立關聯。
用一句話概括事件驅動模式:把 XML 文檔轉換成一串事件,交由獨立的事件處理器決定如何應對。能產生事件的對象叫事件源,能對事件做出響應的對象叫事件處理器。
優點:無需載入整份文檔,資源佔用低,在 Android 等嵌入式環境中尤為推薦。
缺點:不像 DOM 那樣讓文檔長期駐留內存,數據不具持久性;事件處理完若未自行保存,數據即丟失。
適用場景:設備性能受限、文檔較大或只需提取少量字段時。
1. 創建 SAXParserFactory:
SAXParserFactory spf = SAXParserFactory.newInstance();
2. 取得 SAXParser 解析器:
SAXParser saxParser = spf.newSAXParser();
3. 編寫自己的 DefaultHandler 子類,覆蓋關鍵回調:
public class XMLContentHandler extends DefaultHandler {
// 文檔開始,可在此做預處理
@Override
public void startDocument() throws SAXException { ... }
// 元素開始。uri 為命名空間,localName 為不帶前綴的本地名,
// qName 為帶前綴的限定名,attributes 為該元素的屬性集合
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { ... }
// 字符數據。ch 存放內容,start 與 length 標明本次讀到的片段位置,
// 用 new String(ch, start, length) 即可取出文本
@Override
public void characters(char[] ch, int start, int length) throws SAXException { ... }
// 元素結束
@Override
public void endElement(String uri, String localName, String qName) throws SAXException { ... }
}
4. 調用 parse 方法從輸入源解析數據:
saxParser.parse(inputStream, handler); inputStream.close();
也可以改用 XMLReader 的 parse 方法完成同樣的工作。
5. 從 handler 中取出解析結果:
handler.getPersons();
1. 在 res/raw 下新建 itcase.xml(若無 raw 目錄則自行創建):
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person id="23">
<name>liming</name>
<age>30</age>
</person>
<person id="20">
<name>lixiangmei</name>
<age>25</age>
</person>
</persons>
2. 布局中加入兩個觸發按鈕與一個展示用的 TextView:
<Button
android:id="@+id/sax_button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="@dimen/fab_margin"
android:gravity="center_horizontal"
android:text="@string/SAX" />
<Button
android:id="@+id/sax_button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="@dimen/fab_margin"
android:gravity="center_horizontal"
android:text="@string/SAX" />
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
3. 添加 XMLContentHandler 類:
package com.zhangmiao.analyzexmldemo;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.ArrayList;
import java.util.List;
public class XMLContentHandler extends DefaultHandler {
private List<Person> persons = null;
private Person currentPerson;
private String tagName = null;
public List<Person> getPersons() {
return persons;
}
@Override
public void startDocument() throws SAXException {
persons = new ArrayList<>();
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (localName.equals("person")) {
currentPerson = new Person();
currentPerson.setId(Integer.parseInt(attributes.getValue("id")));
}
this.tagName = localName;
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (tagName != null) {
String data = new String(ch, start, length);
if (tagName.equals("name")) {
this.currentPerson.setName(data);
} else if (tagName.equals("age")) {
this.currentPerson.setAge(Short.parseShort(data));
}
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (localName.equals("person")) {
persons.add(currentPerson);
currentPerson = null;
}
this.tagName = null;
}
}
4. 添加 AnalyzeSAX 類,分別演示兩種輸入源:
package com.zhangmiao.analyzexmldemo;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import java.io.InputStream;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class AnalyzeSAX {
public static List<Person> readXML(InputStream inputStream) {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser saxParser = spf.newSAXParser();
XMLContentHandler handler = new XMLContentHandler();
saxParser.parse(inputStream, handler);
inputStream.close();
return handler.getPersons();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static List<Person> readXML(InputSource inputSource) {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser saxParser = spf.newSAXParser();
XMLReader reader = saxParser.getXMLReader();
XMLContentHandler handler = new XMLContentHandler();
reader.setContentHandler(handler);
reader.parse(inputSource);
inputSource.getByteStream().close();
return handler.getPersons();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
5. MainActivity 中觸發解析並展示結果:
package com.zhangmiao.analyzexmldemo;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import org.xml.sax.InputSource;
import java.io.InputStream;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "AnalyzeXMLDemo";
private TextView mTextView;
private InputStream inputStream;
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.v(TAG, "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
Button saxButton1 = (Button) findViewById(R.id.sax_button1);
Button saxButton2 = (Button) findViewById(R.id.sax_button2);
mTextView = (TextView) findViewById(R.id.text);
saxButton1.setOnClickListener(this);
saxButton2.setOnClickListener(this);
}
@Override
public void onClick(View v) {
String result = "";
inputStream = getResources().openRawResource(R.raw.itcase);
switch (v.getId()) {
case R.id.sax_button1:
result += "--------- SAX1 ---------" + "\n";
if (inputStream == null) {
result = "inputStream is null";
} else {
List<Person> personList = AnalyzeSAX.readXML(inputStream);
if (personList != null) {
for (int i = 0; i < personList.size(); i++) {
result += "id = " + personList.get(i).getId()
+ " , name = " + personList.get(i).getName()
+ " , age = " + personList.get(i).getAge() + ".\n";
}
}
}
mTextView.setText(result);
break;
case R.id.sax_button2:
result += "--------- SAX2 ---------" + "\n";
InputSource inputSource = new InputSource();
inputSource.setByteStream(inputStream);
if (inputSource == null) {
result = "inputStream is null";
} else {
List<Person> personList = AnalyzeSAX.readXML(inputSource);
if (personList != null) {
for (int i = 0; i < personList.size(); i++) {
result += "id = " + personList.get(i).getId()
+ " , name = " + personList.get(i).getName()
+ " , age = " + personList.get(i).getAge() + ".\n";
}
}
}
mTextView.setText(result);
break;
default:
break;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
實戰中還有一個細節值得注意:characters() 可能被多次回調,同一段文本並不一定一次讀完。若數據中可能出現實體引用或較長文本,建議用 StringBuilder 累積,並在 endElement() 中統一取值,避免內容被截斷。
參考資料:
https://www.open-open.com/lib/view/open1392780226397.html
https://www.cnblogs.com/weixing/archive/2013/08/07/3243366.html
https://www.tuicool.com/articles/IvQvyq
Android ActionBar 完全使用指南:從啟用到自定義樣式與 Action Provider
本文涵蓋內容 ActionBar 的基本概念與版本差異 啟用 ActionBar 的兩種路線 在 ActionBar 上添加按鈕與點擊事件 自定義樣式、背景與 Tab
Android 百度地圖 SDK 初體驗
準備開發環境 要在 Android 應用中顯示地圖,通常需要先向地圖服務平台申請開發者帳號與 API Key。完成申請後,即可下載 SDK,並將相關 jar 與 so 檔
Android 自定義相機界面實作:圓形拍照鍵與預覽佈局
Android 自定義相機界面實作 想製作類似原生相機的頁面,可以從佈局與自定義背景開始。本文以「圓形拍照鍵」作為切入點,說明如何利用 drawable 資源堆疊出層次感
安卓界面編程入門(三):TextView 及其子類詳解
安卓界面編程入門(三):TextView 及其子類詳解 本篇進入第二組 UI 組件的學習——TextView 及其子類。TextView 是 Android 中最基礎的文