XML 文件本身只承載純資料,若要呈現在網頁上,一般得靠客製的 XSL 文件來轉換,或者手動用 JavaScript 把值讀出來塞進 HTML 的 DOM 樹。
問題在於:使用 XSL 解析時,XML 文件中必須宣告對應的 XSL 檔才能正常顯示。但很多程式動態輸出 XML 時並沒有這層宣告,這時就得另尋途徑載入 XSL。伺服器端固然能用 XML API 處理,本文示範的是純用戶端做法——這樣做的好處是擺脫伺服器平台限制,後端只要吐出 XML(.NET 或 J2EE 皆可),XSL 則可作為串流輸出或直接由瀏覽器載入。
開一個 VS2003 的 Web 專案,命名為 XMLTest。
把專案目錄下 WebForm1.aspx 的內容全部刪除,只保留最上方那一行宣告:
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="XMLTest.WebForm1" %>
XmlDocument doc = new XmlDocument(); string xmlfile = string.Empty; xmlfile = Context.Request.PhysicalApplicationPath + (Request.QueryString["sel"].ToString() == "xml" ? "\\hello.xml" : "\\hello.xsl"); doc.Load(xmlfile); Response.Write(doc.InnerXml);
同一支程式依 sel 參數決定要回傳 XML 還是 XSL,用戶端就能用兩個請求分別把兩份檔案抓回來。
於專案根目錄新增 test.htm 並設為首頁,核心腳本如下:
<input type="button" value="執行" onclick="GetXML()">
<div id="resTree"></div>
<script language="JScript">
var srcTree, xsltTree, xt;
var http_request = false;
function GetXML() {
srcTree = new ActiveXObject("Msxml2.FreeThreadedDOMDocument");
srcTree.async = false;
xsltTree = new ActiveXObject("Msxml2.FreeThreadedDOMDocument");
xsltTree.async = false;
xt = new ActiveXObject("MSXML2.XSLTemplate");
resTree.innerHTML = "";
makeRequest("WebForm1.aspx?sel=xml", GetXML_CB);
}
function makeRequest(url, callback) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla、Safari 等
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('無法建立 XMLHTTP 物件');
return false;
}
http_request.onreadystatechange = callback;
http_request.open('GET', url, true);
http_request.send(null);
}
function GetXML_CB() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
srcTree.loadXML(http_request.responseText);
makeRequest("WebForm1.aspx?sel=xsl", GetXsl_CB);
} else {
alert('請求發生問題');
}
}
}
function GetXsl_CB() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
xsltTree.loadXML(http_request.responseText);
xt.stylesheet = xsltTree;
var proc = xt.createProcessor();
proc.input = srcTree;
proc.transformToHTML();
resTree.innerHTML = proc.output;
} else {
alert('請求發生問題');
}
}
}
</script>
流程是這樣的:先非同步抓取 XML,成功後在回呼函式裡接著抓 XSL,兩份都到手後再套用轉換,把結果寫進 resTree。整條鏈路由回呼函式串接,完全不必等頁面重新載入。
示範用的 XML 刻意不宣告對應的 XSL 檔,正是為了凸顯動態載入的必要性:
<?XML version='1.0'?> <breakfast-menu> <food> <name>Belgian Waffles</name> <price>$5.95</price> <description>Two of our famous Belgian Waffles with plenty of real maple syrup.</description> <calories>650</calories> </food> <food> <name>Strawberry Belgian Waffles</name> <price>$7.95</price> <description>Light Belgian waffles covered with strawberries and whipped cream.</description> <calories>900</calories> </food> <food> <name>French Toast</name> <price>$4.50</price> <description>Thick slices made from our homemade sourdough bread.</description> <calories>600</calories> </food> <food> <name>Homestyle Breakfast</name> <price>$6.95</price> <description>Two eggs, bacon or sausage, toast, and our ever-popular hash browns.</description> <calories>950</calories> </food> </breakfast-menu>
負責呈現的 XSL 用 for-each 遍歷 food 節點,把每道菜排成一塊底色區塊加上說明文字:
<?XML version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="https://www.w3.org/1999/XSL/Transform"> <xsl:template match="/breakfast-menu"> <xsl:for-each select="food"> <DIV STYLE="background-color:teal; color:white; padding:4px"> <SPAN STYLE="font-weight:bold"> <xsl:value-of select="name"/> </SPAN> 至 <xsl:value-of select="price"/> </DIV> <DIV STYLE="margin-left:20px; font-size:10pt"> <xsl:value-of select="description"/> <SPAN STYLE="font-style:italic"> <xsl:value-of select="calories"/> </SPAN> </DIV> </xsl:for-each> </xsl:template> </xsl:stylesheet>
第一,載入 XML 時雖常用 Msxml2.Document 組件,但要在執行期動態套用 XSL,就必須改用 Msxml2.FreeThreadedDOMDocument 這種自由執行緒組件,並搭配 MSXML2.XSLTemplate 模板組件;透過 XSLTemplate 的 transform 系列方法,即可完成動態轉換。
第二,從 IE5 起系統預設的 XML 組件是 msxml2。若要用更新的版本,需另行安裝對應的 msxml 組件包並指定新名稱,例如 Msxml2.FreeThreadedDOMDocument.4.0。
整體而言,這種做法把轉換責任從伺服器搬到瀏覽器,讓後端維持單純——只負責輸出資料,版面則交給 XSL 決定。