DOM(Document Object Model)是 W3C 定義的、與平台及語言無關的 XML 文件表示方式。它把整份 XML 文件組織成一棵由節點組成的樹,每個節點都是資訊片段,開發者可以從根元素一路往下遍歷、取值。
跟 SAX 這種「事件驅動、邊讀邊丟」的串流解析比起來,DOM 的取用方式直覺得多:想拿哪個節點就沿著樹走。代價是它會把整份文件一次載入記憶體,因此檔案大時記憶體開銷明顯,這也是 DOM 最常被詬病的一點。
學會 DOM 解析 XML 的基本流程,並用它拆解 Google 早期提供的天氣查詢介面,把未來幾天的預報資料抓出來。
介面網址形如:https://www.google.com/ig/api?hl=zh_CN&weather=wuhan
網址尾端的 wuhan 就是城市拼音,想看北京的資料,把它換成 beijing 即可。這個介面會回傳四天份的天氣預報(此為 Google 早年開放的服務,現已不再提供,本文保留作為 DOM 解析的練習題材)。
回傳 XML 的根元素是 xml_api_reply,也就是整棵樹的根,其後的節點都由此展開;我們真正要挖的是 forecast_conditions 底下的資料。
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document document = builder.parse(
new InputSource(new InputStreamReader(lianJie(strUrl))));
拿到 Document 之後,就能搭配 NodeList 與 Node 逐層取出節點與屬性值。
package com.study.weather;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class Weather {
public InputStream lianJie(String strUrl) throws IOException {
URL url = new URL(strUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
if (is != null) {
return is;
}
return null;
}
public void resolutionXML(String strUrl)
throws ParserConfigurationException, SAXException, IOException {
WeatherData wd = new WeatherData();
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document document = builder.parse(
new InputSource(new InputStreamReader(lianJie(strUrl))));
// 取得根節點 xml_api_reply
Element rootElement = document.getDocumentElement();
System.out.println(rootElement.getNodeName());
// 取得 weather 節點
Node weatherNode = rootElement.getElementsByTagName("weather").item(0);
System.out.println(weatherNode.getNodeName());
// weather 底下的子節點集合
NodeList nodeForecastWeathers = weatherNode.getChildNodes();
for (int i = 0; i < nodeForecastWeathers.getLength(); i++) {
Node nodeForecastWeather = nodeForecastWeathers.item(i);
// 只挑元素節點,且名稱為 forecast_conditions
if (nodeForecastWeather.getNodeType() == Node.ELEMENT_NODE
&& nodeForecastWeather.getNodeName().equals("forecast_conditions")) {
NodeList nodeListForecastConditions = nodeForecastWeather.getChildNodes();
for (int j = 0; j < nodeListForecastConditions.getLength(); j++) {
Node data = nodeListForecastConditions.item(j);
if (data.getNodeName().equals("day_of_week")) {
wd.setDayOfWeek(data.getAttributes().getNamedItem("data").getNodeValue());
} else if (data.getNodeName().equals("low")) {
wd.setLow(data.getAttributes().item(0).getNodeValue());
} else if (data.getNodeName().equals("high")) {
wd.setHigh(data.getAttributes().item(0).getNodeValue());
} else if (data.getNodeName().equals("condition")) {
wd.setConditionData(data.getAttributes().item(0).getNodeValue());
}
}
System.out.println(wd.printWeatheaInfo());
}
}
}
public static void main(String[] args)
throws ParserConfigurationException, SAXException, IOException {
Weather weather = new Weather();
weather.resolutionXML("https://www.google.com/ig/api?hl=zh_CN&weather=wuhan");
}
class WeatherData {
String dayOfWeek;
String low;
String high;
String conditionData;
public void setDayOfWeek(String dayOfWeek) { this.dayOfWeek = dayOfWeek; }
public void setLow(String low) { this.low = low; }
public void setHigh(String high) { this.high = high; }
public void setConditionData(String conditionData) { this.conditionData = conditionData; }
public String printWeatheaInfo() {
return dayOfWeek + "\n" + "溫度: " + low + "~~" + high
+ " \n天氣情況: " + conditionData;
}
}
}
天氣資訊並不是放在節點文字裡,而是藏在屬性 data 上,所以要透過 getAttributes() 取值;low、high、condition 只有一個屬性,用 item(0) 即可。
另外,遍歷 getChildNodes() 時務必先判斷 getNodeType() == Node.ELEMENT_NODE,因為換行與縮排也會被當成文字節點,不篩掉就會多跑好幾輪無意義的迴圈。
執行結果顯示,四天份的星期、低溫、高溫與天氣狀況都能正確解析出來。