XML 解析在網路上已經有汗牛充棟的討論,這篇就當作自己的複習筆記,直接上程式碼。
SAX 解析的關鍵在於「事件驅動」:你繼承 DefaultHandler,針對文件開始、元素開始、字元內容、元素結束等事件各自實作反應,解析器便會在讀到對應位置時回呼你的方法。
public class ChatLogContentHandler extends DefaultHandler {
ChatInfo info = null;
ArrayList<ChatInfo> infos = null;
String tagName = null;
public ChatLogContentHandler(ArrayList<ChatInfo> infos) {
super();
this.infos = infos;
}
public void startDocument() throws SAXException {
System.out.println("解析 XML 開始");
}
public void endDocument() throws SAXException {
System.out.println("解析完畢");
}
public void startElement(String namespaceURI, String localName,
String qName, Attributes attr) throws SAXException {
tagName = localName;
if (tagName.equals("chatinfo")) {
info = new ChatInfo();
}
}
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (qName.equals("chatinfo")) {
infos.add(info);
}
tagName = "";
}
public void characters(char[] ch, int start, int length) throws SAXException {
String temp = null;
if (tagName.equals("name")) {
temp = new String(ch, start, length);
info.setChatName(temp);
} else if (tagName.equals("time")) {
temp = new String(ch, start, length);
info.setChatTime(temp);
} else if (tagName.equals("info")) {
temp = new String(ch, start, length);
info.setChatString(temp);
}
}
}
流程其實很直白:遇到 <chatinfo> 就 new 一個物件,遇到 name/time/info 就把字元內容塞進對應欄位,遇到 </chatinfo> 就把物件放進清單。用一個 tagName 變數記錄「目前人在哪個標籤裡」,是這類解析最常見的寫法。
它不必在開場就把整份檔案讀進記憶體,而是邊讀邊解析、逐筆產出。這也是為什麼前一篇文章中,寫入 XML 時一定要照規定換行、縮排——標籤各佔一行,才能讓逐行式的解析穩定運作。
如果檔案被壓成一行,例如:
<chatlog><chatinfo><time>12:00</time></chatinfo></chatlog>
解析時就會出錯。因此「寫入時的格式」與「讀取時的解析策略」其實是一體兩面,設計檔案格式時不能只看一端。
另外提醒一個實務細節:characters() 可能被呼叫多次才構成一個完整文字節點,若資料中出現實體或較長內容,建議用 StringBuffer 累積,並在 endElement 時才取值,會比直接 new String 更保險。