XML 本身只描述資料,不含任何呈現資訊。要讓它在瀏覽器裡變成好看的畫面,最主流的做法是搭配 XSL。XSL 是首選的 XML 樣式表語言,比 CSS 完善得多——其中一個典型用法,就是在瀏覽器顯示 XML 檔之前先把它轉換成 HTML。
<?xml version="1.0" encoding="ISO-8859-1" ?>
<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>
直接在瀏覽器打開,看到的是一團沒有格式的標籤樹,可讀性極差。
這份樣式表用 xsl:for-each 遍歷每個 food 節點,把品名與價格放進深色標題列,描述與熱量放在下方,做出菜單的視覺層次。
<?xml version="1.0" encoding="ISO-8859-1" ?>
<html xsl:version="1.0"
xmlns:xsl="https://www.w3.org/1999/XSL/Transform"
xmlns="https://www.w3.org/1999/xhtml">
<body style="font-family:Arial,helvetica,sans-serif;font-size:12pt; background-color:#EEEEEE">
<xsl:for-each select="breakfast_menu/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" /> calories per serving)
</span>
</div>
</xsl:for-each>
</body>
</html>
關鍵在第二行的 xml-stylesheet 處理指令,它告訴瀏覽器該用哪一份樣式表來呈現這份 XML:
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="simple.xsl"?>
<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>two of our famous Belgian Waffles</description>
<calories>650</calories>
</food>
</breakfast_menu>
用支援 XSLT 的瀏覽器打開這份 XML,就會看到排好版的菜單,而不是原始標籤。
第一,xsl:value-of 只取值,xsl:for-each 做迭代,這兩個加上 xsl:template 的樣板匹配,就構成 XSLT 九成以上的日常用法。第二,樣式表本身也必須是格式良好的 XML,寫錯一個閉合標籤就會整份失效。第三,命名空間宣告 xmlns:xsl="https://www.w3.org/1999/XSL/Transform" 不可省略,且版本號要對得上你的處理器。第四,這種「用戶端轉換」把轉換負擔放在瀏覽器;若對象包含不支援 XSLT 的環境(例如部分行動裝置或需要 SEO 的公開頁面),改在伺服器端轉換成 HTML 再輸出會更穩妥。