Android 上解析 XML 常見三種做法:SAX、DOM 與 PULL。SAX 佔用記憶體少、解析速度快,採用「事件啟動」的模式——程式由上往下掃過文件,遇到元素開始、字元、元素結束就觸發對應的 callback,不必把整份文件一次載入記憶體,因此也是官方推薦的方式之一。代價是無法回頭隨機存取,必須自己把需要的資料存起來。
以下是一份來自考試天氣服務的資料(為求簡潔,僅列出主要欄位,實際文件還包含紫外线、洗车、感冒等指標):
<?xml version="1.0" encoding="UTF-8"?>
<!-- published at 2011-12-14 14:55:05 -->
<Profiles>
<Weather>
<city>廣州</city>
<status1>多雲</status1>
<status2>陰</status2>
<figure1>duoyun</figure1>
<figure2>yin</figure2>
<direction1>無持續風向</direction1>
<temperature1>20</temperature1>
<temperature2>12</temperature2>
<chy_shuoming>套裝、夾衣、風衣、夾克衫、西服套裝、馬甲襯衫配長褲</chy_shuoming>
<pollution_l>一般</pollution_l>
<ssd_s>適宜在自然環境及露天場所活動。</ssd_s>
<gm_l>低發期</gm_l>
<yd_l>比較適宜</yd_l>
<savedate_weather>2011-12-14</savedate_weather>
</Weather>
</Profiles>
關鍵技巧是用一個 preTag 變數記住「目前所在的節點名稱」。因為 characters() 只給你字元內容,不告訴你它屬於哪個標籤,必須靠 startElement() 先把標籤名存起來。
public class WeatherHandler extends DefaultHandler {
private Weather weather;
private String preTag = null; // 記錄解析時的上一個節點名稱
@Override
public void startDocument() throws SAXException {
weather = new Weather();
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
preTag = qName;
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
String result = new String(ch, start, length);
if (preTag.equals(Constant.City)) {
if (weather.getCity() == null) weather.setCity(result);
}
if (preTag.equals(Constant.Status1)) {
if (weather.getStatus1() == null) weather.setStatus1(result);
}
if (preTag.equals(Constant.Temperature1)) {
if (weather.getTemperature1() == null) weather.setTemperature1(result);
}
// 其餘欄位(status2、figure1、direction1、power1、ssd、ktk、
// pollution、xcz、chy、gm、yd 等)皆依相同模式判斷 preTag 後赋值
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equals("Profiles")) {
preTag = null;
}
}
@Override
public void endDocument() throws SAXException {
super.endDocument();
System.out.println("城市:" + weather.getCity());
System.out.println("白天:" + weather.getStatus1());
System.out.println("夜間:" + weather.getStatus2());
}
}
InputStream inStream = getClass().getClassLoader()
.getResourceAsStream("weather.xml");
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setContentHandler(new WeatherHandler());
reader.parse(new InputSource(inStream));
} catch (Exception e) {
e.printStackTrace();
}
第一,characters() 可能被呼叫多次,同一段文字會被切成好幾塊,因此判斷 getXxx() == null 才赋值,可避免拿到空白片段。第二,範例中的 getResourceAsStream() 是 Java SE 的用法;在 Android 上,若檔案放在 assets 或 res/raw,應改用 AssetManager.open() 或 Resources.openRawResource() 取得串流,並記得在解析結束後關閉它。