對於講求速度與貼近使用者的輕量應用來說,XML 確實顯得笨重——解析起來既耗記憶體又複雜,就像花大錢買了套功能滿漢全席的軟體,卻有八成功能用不到,還白白耗著 CPU 與記憶體。(以上僅為個人觀點。)設定檔用 XML 其實還不錯,因為它通常不大、可讀性強;但如果是解析豆瓣 API 回傳的 XML,實在很想說一句:與其用 XML,不如提供個 JSON 版的 API 吧。
解析豆瓣回傳的 XML,實在不想動用 DOM 這號重量級傢伙。我傾向使用 SAX 解析,但面臨一個問題:需要依據 XML 節點的名稱與屬性值(一個或多個)來判斷當前的值是不是我要的。第一反應是考慮 XPath,後來覺得不如自己動手做一個,權當是按需定制的輕量級 XPath。
首先定義 XMLSearchUnit 類,它的每個實例用來描述一項需要在 XML 中搜尋的值,目標可以是節點的值,也可以是節點的屬性。
package com.deepnighttwo.resourceresolver.douban.resolver.utils;
import java.util.HashMap;
import java.util.Map;
import org.xml.sax.Attributes;
/**
* 代表一項搜尋任務,目標可以是節點的值或節點的屬性。
*/
public class XMLSearchUnit {
// 搜尋時要比對的屬性鍵值對
private Map<String, String> attributeMatchValidation = new HashMap<String, String>();
// 若目標是屬性,則設為該屬性名;若為 null 或空,則表示目標是節點值
private String expectedAttr;
// XML 路徑,格式為:/node_name/node_name/...
private String xmlPath;
public XMLSearchUnit(String xmlPath) {
this.xmlPath = xmlPath;
}
/**
* 判斷目前節點是否符合搜尋條件:路徑正確且屬性值相符。
*/
public boolean match(String path, Attributes attributes) {
if (xmlPath.equals(path) == false) {
return false;
}
for (String key : attributeMatchValidation.keySet()) {
String exp = attributeMatchValidation.get(key);
String compare = attributes.getValue(key);
if (exp.equalsIgnoreCase(compare) == false) {
return false;
}
}
return true;
}
public Map<String, String> getAttributeMatchValidation() {
return attributeMatchValidation;
}
public void addAttributeValidation(String key, String value) {
attributeMatchValidation.put(key, value);
}
public String getXmlPath() {
return xmlPath;
}
public String getExpectedAttr() {
return expectedAttr;
}
/**
* 若目標是節點值,設為 null;若目標是屬性值,設為該屬性名。
*/
public void setExpectedAttr(String expectedAttr) {
this.expectedAttr = expectedAttr;
}
}
這個類很簡單:用一個 HashMap 保存要比對的屬性鍵值對,用一個字串表示期待的屬性名,再用一個字串表示期待的節點路徑。實作中還需補上 hashCode() 與 equals(),以便把 XMLSearchUnit 當作 HashMap 的鍵來快取結果。
接下來就是在 SAX 裡用這些單元去搜尋。核心概念是:一邊解析一邊維護目前的節點路徑,遇到符合條件的節點就記錄下來;若是節點值,得等到讀到文字時才知道,若是屬性值,當下即可取得。當所有搜尋單元都找到值後,就能提前跳過剩餘內容。
package com.deepnighttwo.resourceresolver.douban.resolver.utils;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
/**
* 與 XMLSearchUnit 搭配運作的 SAX 解析器。
*/
public class DoubanSearchParser extends DefaultHandler {
// 建立並初始化搜尋單元
public static final XMLSearchUnit DETAILS_LINK_API_PATH = new XMLSearchUnit("/feed/entry/id");
public static final XMLSearchUnit DETAILS_CONTENT_PATH = new XMLSearchUnit("/entry/summary");
public static final XMLSearchUnit DETAILS_TITLE_PATH = new XMLSearchUnit("/entry/title");
public static final XMLSearchUnit DETAILS_CHINESE_NAME_PATH = new XMLSearchUnit("/entry/db:attribute");
public static final XMLSearchUnit DETAILS_RATINGE_PATH = new XMLSearchUnit("/entry/gd:rating");
public static final XMLSearchUnit DETAILS_RATINGE_RATER_COUNT_PATH = new XMLSearchUnit("/entry/gd:rating");
public static final XMLSearchUnit DETAILS_LINK_URL_PATH = new XMLSearchUnit("/feed/entry/link");
static {
DETAILS_LINK_URL_PATH.addAttributeValidation("rel", "alternate");
DETAILS_LINK_URL_PATH.setExpectedAttr("href");
DETAILS_CHINESE_NAME_PATH.addAttributeValidation("lang", "zh_CN");
DETAILS_CHINESE_NAME_PATH.addAttributeValidation("name", "aka");
DETAILS_RATINGE_PATH.setExpectedAttr("average");
DETAILS_RATINGE_RATER_COUNT_PATH.setExpectedAttr("numRaters");
}
// 保存搜尋單元與結果值的對應
private Map<XMLSearchUnit, String> results = new HashMap<XMLSearchUnit, String>();
// 搜尋單元計數器,為 0 表示全部找到,可跳過後續內容
private int count = 0;
private StringBuilder path = new StringBuilder();
private static final String pathSeparater = "/";
private XMLSearchUnit[] searchUnits;
List<XMLSearchUnit> foundItems = new ArrayList<XMLSearchUnit>();
/**
* 建構子,接受 XML 輸入流與零個以上的搜尋單元。
*/
public Map<XMLSearchUnit, String> parseResults(InputStream input, XMLSearchUnit... expectedPath) {
for (XMLSearchUnit search : expectedPath) {
results.put(search, null);
}
searchUnits = expectedPath;
count = expectedPath.length;
XMLReader xmlReader = null;
try {
SAXParserFactory spfactory = SAXParserFactory.newInstance();
spfactory.setValidating(false);
SAXParser saxParser = spfactory.newSAXParser();
xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(this);
xmlReader.parse(new InputSource(input));
} catch (Exception e) {
System.err.println(e);
System.exit(1);
}
return results;
}
private void addToPath(String addPath) {
path.append(pathSeparater).append(addPath.toLowerCase());
}
private void popPath() {
int index = path.lastIndexOf(pathSeparater);
path.delete(index, path.length());
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
foundItems.clear();
if (count == 0) {
return;
}
// 更新路徑
addToPath(qName);
List<XMLSearchUnit> foundAttrItems = null;
// 檢查目前節點是否符合搜尋單元
for (XMLSearchUnit unit : searchUnits) {
if (unit.match(path.toString(), attributes) == true) {
if (unit.getExpectedAttr() == null) {
foundItems.add(unit);
} else {
if (foundAttrItems == null) {
foundAttrItems = new ArrayList<XMLSearchUnit>();
}
foundAttrItems.add(unit);
}
}
}
// 沒有屬性符合則返回
if (foundAttrItems == null) {
return;
}
// 用屬性值填入搜尋單元並更新計數
for (XMLSearchUnit attrUnit : foundAttrItems) {
String attrValue = attributes.getValue(attrUnit.getExpectedAttr());
if (results.get(attrUnit) == null) {
count--;
}
results.put(attrUnit, attrValue);
count--;
}
}
/**
* 若目前節點符合,節點值即有用,予以保存。
*/
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (count == 0) {
return;
}
if (foundItems.size() == 0) {
return;
}
for (XMLSearchUnit unit : foundItems) {
String content = new String(ch, start, length);
if (results.get(unit) == null) {
count--;
}
results.put(unit, content);
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
foundItems.clear();
if (count == 0) {
return;
}
popPath();
}
}
這套做法的精髓在於:以 SAX 的事件流為骨架,自訂一個輕量版的 XPath——用字串維護路徑、用屬性比對做條件篩選,既避開了 DOM 的記憶體負擔,又能精準抓出你要的節點與屬性值。等所有目標都命中,還能提前收尾,省去不必要的解析。