編輯:Android 開發實例
在 Android 平台上操作 XML 的方式不少,最常見的兩條路是 SAX(Simple API for XML)與 DOM(Document Object Model)。
SAX 的特性是「邊讀邊觸發事件」:解析器逐段讀取 XML 檔案,每遇到一個元素就發出事件,由我們在事件回呼中即時處理當前讀到的內容。這點與 DOM 有本質差異——DOM 會先把整份文件全部載入記憶體、建成一棵完整的節點樹,之後才讓你操作。
這個差異在實務上很關鍵:SAX 的記憶體用量幾乎與文件大小無關,適合處理龐大的 XML 或串流資料;DOM 則勝在可以隨意往前後走訪節點、也能修改結構,代價是記憶體開銷大。以下範例走的是 SAX 路線。
例子以讀取 Google 天氣預報為題材,XML 來源是:
https://www.google.com/ig/api?weather=beijing&hl=zh-cn
程式先透過網路把天氣 XML 抓回來,再用 SAX 解析。這裡只處理了即時天氣,預報部分留待日後補齊:
第一步,先依 XML 的結構抽出一個承載用的類別。抓回來的 XML 長這樣(不同時間抓到的內容會有差異,但格式是一致的):
<?xml version="1.0" ?> <xml_api_reply version="1"> <weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0"> <forecast_information> <city data="Beijing, Beijing" /> <postal_code data="beijing" /> <forecast_date data="2010-12-27" /> <current_date_time data="2010-12-28 04:00:00 +0000" /> <unit_system data="SI" /> </forecast_information> <current_conditions> <condition data="晴" /> <temp_f data="28" /> <temp_c data="-2" /> <humidity data="濕度: 27%" /> <icon data="/ig/images/weather/sunny.gif" /> <wind_condition data="風向: 西北、風速:7 米/秒" /> </current_conditions> <forecast_conditions> <day_of_week data="周一" /> <low data="-12" /> <high data="6" /> <icon data="/ig/images/weather/sunny.gif" /> <condition data="晴" /> </forecast_conditions> </weather> </xml_api_reply>
依這個結構抽出的類別如下:
package com.SAXXMLReader;
public class NowWeather {
private String condition;
private String temp_f;
private String temp_c;
private String humidity;
private String icon;
private String wind_condition;
public NowWeather() {
}
public void setcondition(String condition) { this.condition = condition; }
public void settempf(String temp_f) { this.temp_f = temp_f; }
public void settempc(String temp_c) { this.temp_c = temp_c; }
public void sethumidity(String humidity) { this.humidity = humidity; }
public void seticon(String icon) { this.icon = icon; }
public void setwindcondition(String wind_condition) { this.wind_condition = wind_condition; }
public String getNowWeather() {
StringBuilder strBuilder = new StringBuilder();
strBuilder.append(condition + "\n");
strBuilder.append(temp_f + "\n");
strBuilder.append(temp_c + "\n");
strBuilder.append(humidity + "\n");
strBuilder.append(icon + "\n");
strBuilder.append(wind_condition + "\n");
return strBuilder.toString();
}
}
這個類別只負責裝資料,實際的欄位設計與存取方式可依個人習慣調整。
接著是重點:SAX 要求我們提供一個繼承 DefaultHandler 的類別,把解析過程中感興趣的事件攔下來:
package com.SAXXMLReader;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class WeatherHandler extends DefaultHandler {
private final String CURRENT_CONDITIONS = "current_conditions"; // 即時天氣
private final String forecast_conditions = "forecast_conditions"; // 預報天氣
// 是否正處於即時天氣區段
private boolean is_Current_Conditions = false;
// 是否正處於預報天氣區段
private boolean is_Forecast_Conditions = false;
NowWeather nowWeather = new NowWeather();
public WeatherHandler() {
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
String dataAttribute = "OK";
if (localName.equals(CURRENT_CONDITIONS)) {
is_Current_Conditions = true;
} else if (localName.equals(forecast_conditions)) {
is_Current_Conditions = false;
} else {
dataAttribute = attributes.getValue("data");
if (this.is_Current_Conditions) {
// 這份 XML 的實際數值都放在 data 屬性裡
if (localName.equals("condition")) {
this.nowWeather.setcondition(dataAttribute);
} else if (localName.equals("temp_f")) {
this.nowWeather.settempf(dataAttribute);
} else if (localName.equals("temp_c")) {
this.nowWeather.settempc(dataAttribute);
} else if (localName.equals("humidity")) {
this.nowWeather.sethumidity(dataAttribute);
} else if (localName.equals("icon")) {
this.nowWeather.seticon(dataAttribute);
} else if (localName.equals("wind_condition")) {
this.nowWeather.setwindcondition(dataAttribute);
}
}
}
}
public String getNowWeather() {
return nowWeather.getNowWeather();
}
}
如此一來,XML 的內容就被解析並存進我們自己抽出的類別裡,供後續呼叫使用。
最後是驅動部分——建立解析器、掛上 handler、把網路串流餵進去:
SAXParserFactory faction = SAXParserFactory.newInstance(); SAXParser parser = faction.newSAXParser(); WeatherHandler handler = new WeatherHandler(); XMLReader reader = parser.getXMLReader(); reader.setContentHandler(handler); URL url = new URL(SRC); HttpURLConnection httpconn = (HttpURLConnection) url.openConnection(); InputStream inStream = httpconn.getInputStream(); InputStreamReader isReader = new InputStreamReader(inStream, "GBK"); InputSource inputSource = new InputSource(isReader); reader.parse(inputSource); text1.setText(handler.getNowWeather());
這裡直接解析網路上的 XML;如果要讀的是本機檔案,做法完全一樣,只要把 inStream 換成 getResources().openRawResource(...) 即可。
因為趕時間,這份程式碼在命名與結構上未必規整,還請多包涵。若發現任何錯誤,也歡迎指正。
Android 取得 App 應用程式佔用大小的方法(反射 + AIDL)
PackageManager 雖然內建了計算套件大小的能力,但 getPackageSizeInfo 是隱藏 API,一般應用沒有權限直接呼叫。繞過限制的思路是:透過 J
Android 模擬定位實作教學:權限宣告、狀態偵測與座標注入
想在 App 裡驗證定位功能,卻不方便真的出門跑一條路線?Android 系統本身內建了「模擬位置」機制:只要在開發者選項中指定一支代理程式,系統 GPS 就會回報你自己
Android 自定義 ImageView 實現透明圓弧與弧形文字
最近因為項目需求,需要在 ImageView 上疊加一層透明圓弧,並且沿著圓弧方向顯示相應的文字,效果如下圖所示: 拿到這個需求,我最直覺的思路就是自定義一個 Imag
Android JSON 解析:JSONObject 與 JSONArray 的實際應用
JSON 是 Android 開發中常見的資料格式。當 App 需要從網路取得資料時,後端通常會回傳 JSON 字串,開發者再透過 JSONObject 與 JSONAr