在 Ajax 中使用 XSLT 轉換 XML
本系列的 第 1 部分 提出了問題說明:建立便於插入任何 Web 頁面的天氣面板。天氣面板採用 Ajax 技術實現,利用 United States National Weather Service (NWS) 提供的資料。NWS 資料以 XML 格式提供,每 15 分鐘更新一次。
本系列文章分析了實現天氣面板的四種不同方法。第一部分中介紹的一種辦法是利用一種 Apache Web 服務器規則將 NWS XML 資料代理給瀏覽器。然後通過 JavaScript 代碼從 DOM 提取需要的資料,轉變為 HTML 格式再顯示出來。
這一部分介紹第二和 第三種方法。這兩種辦法有一點是共同的,即都使用 XSLT。
XSLT
XSLT 是一種查詢 XML 並將其轉換成其他格式的語言。這恰恰是我們所要對天氣資料做的 工作 — 以 XML 格式儲存,但需要某種對使用者(或者瀏覽器)更友好的格式。 NWS 資料中有些是天氣面板所不需要的。需要某種技術提取需要的資料。XSLT 可以同 時滿足這兩方面的要求。
本教程不是為了詳細介紹 XSLT。關於 XSLT 的更多資訊請參閱 developerWorks 文章 “What kind of language is XSLT?” (參見 參考資料)。
和其他很多電腦語言不同,XSLT 文法是有效 XML。如果習慣於 C、Java™、Perl 或 Python 語言,可能會造成一點麻煩。
由於這兩種方法都使用 XSLT,我們首先來看看它。然後再介紹如何納入總體解決方案。
使用 XSLT 轉換資料
首先看看 NWS XML 資料格式。清單 1 顯示了 壓縮後的例子。
清單 1. 樣本 NWS XML 資料檔案 KNGU.xml(有刪減)
<?xml version="1.0" encoding="ISO-8859-1"? >
<current_observation version="1.0"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation=
"http://www.weather.gov/data/current_obs/current_observation.xsd">
<credit>NOAA's National Weather Service</credit>
<credit_URL>http://weather.gov/</credit_URL>
<image>
<url>gif/xml_logo.gif</url>
<title>NOAA's National Weather Service</title>
<link>http://weather.gov</link>
</image>
<suggested_pickup>15 minutes after the hour</suggested_pickup>
<suggested_pickup_period>60</suggested_pickup_period>
<location>Norfolk, Naval Air Station, VA</location>
<station_id>KNGU</station_id>
<latitude>36.94</latitude>
<longitude>-76.28</longitude>
<observation_time>
Last Updated on Jan 7, 2:53 pm EST
</observation_time>
<observation_time_rfc822>
Mon, 7 Jan 2008 14:53:00 -0500 EST
</observation_time_rfc822>
<weather>Fair</weather>
<temperature_string>74 F (23 C)</temperature_string>
<temp_f>74</temp_f>
<temp_c>23</temp_c>
<relative_humidity>34</relative_humidity>
<wind_string>From the Southwest at 9 Gusting to 18 MPH</wind_string>
<wind_dir>Southwest</wind_dir>
<wind_degrees>240</wind_degrees>
<visibility_mi>10.00</visibility_mi>
<icon_url_base>
http://weather.gov/weather/images/fcicons/
</icon_url_base>
<icon_url_name>
skc.jpg
</icon_url_name>
<disclaimer_url>http://weather.gov/disclaimer.html</disclaimer_url>
<copyright_url>http://weather.gov/disclaimer.html</copyright_url>
<privacy_policy_url>http://weather.gov/notice.html</privacy_policy_url>
</current_observation>