XML 檔本身只承載純資料,若要呈現在網頁上,通常得靠一份客製的 XSL 來轉換,或是以 JavaScript 手動取值塞進 DOM。而用 XSL 有一個前提:XML 檔中必須用 <?xml-stylesheet?> 指定對應的樣式表,否則瀏覽器不會自動套用。
問題就在這裡——很多時候 XML 是程式動態產生的,裡頭根本沒有指定樣式表。這種情況下就得另尋出路。伺服器端當然可以用 XML API 處理,但本文要談的是純用戶端方案:由瀏覽器以非同步方式分別抓取 XML 與 XSL,再自行完成轉換。這種做法的好處是擺脫了伺服器平台的限制,後端無論是 .NET 還是 J2EE,只要老實吐出 XML 與 XSL 即可。
開一個 VS2003 的 Web 專案,命名為 XMLTest。
把 WebForm1.aspx 的內容全部刪除,只留最上方那一行宣告:
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="XMLTest.WebForm1" %>
這個端點根據查詢參數 sel 決定要回傳哪一份檔案,方便前端用同一個 URL 分別抓取:
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);
<html>
<head>
<title></title>
</head>
<body>
<div id="resTree"</div>
<input type="button" value="執行" onclick="GetXML()"><br>
<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); // 接著抓 XSL
} 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.transform();
resTree.innerHTML = proc.output;
} else {
alert('請求發生問題');
}
}
}
</script>
</body>
</html>
請注意,這份 XML 裡完全沒有指定對應的樣式表——正是為了示範「動態套用」的必要性:
<?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>Berry-Berry Belgian Waffles</name>
<price>$8.95</price>
<description>Light Belgian waffles covered with an assortment of fresh berries 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>
<?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; color:white"><xsl:value-of select="name"/></span>
- <xsl:value-of select="price"/>
</div>
<div style="margin-left:20px; margin-bottom:1em; 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>
運行專案,按下執行鈕,早餐菜單就會以格式化後的樣子出現在頁面上。
必須用 FreeThreadedDOMDocument:一般我們習慣用 Msxml2.DOMDocument 載入 XML,但要在同一份程式裡同時持有 XML、XSL 並交給模板處理,就必須改用自由執行緒的 Msxml2.FreeThreadedDOMDocument。原因是 XSLTemplate 的 processor 會跨執行緒存取這些 DOM,非自由執行緒的版本會直接拋出錯誤。
樣式表要掛在 XSLTemplate 上:先設定 xt.stylesheet,再呼叫 createProcessor() 取得處理器,指定 input 後執行 transform(),結果從 output 取出。這條鏈路是 MSXML 3 之後才有的用法。
元件版本:自 IE5 起,系統預設的 XML 元件就是 msxml2。若要使用更新的版本,需另外安裝對應的 MSXML 套件,並在程式化名稱後加上版本號,例如 Msxml2.FreeThreadedDOMDocument.4.0。
非同步的意義:把 open() 的第三個參數設為 true,抓取 XML 完成後才接著抓 XSL,兩段請求串成一個非同步鏈。這樣頁面不會被凍結,使用者體驗明顯更好。
值得一提的是,這套「後端只出資料、前端負責呈現」的分工,其實正是後來 AJAX 架構的雛形。今日若要重寫同樣的功能,用 fetch 搭配 DOMParser 與 XSLTProcessor 就能完成,而且不必再依賴 ActiveX——那是 IE 專屬的途徑,在其他瀏覽器上完全無法運作。