這個做法很輕鬆,只要設定好 XML 與 XSLT 檔,幾乎不必改動程式。以下提供 PHP 程式、XML 文件與 XSLT 樣式表的完整範例。(註:部分主機若不支援 XSLT 模組,需先載入對應元件。)
<?php$xslstring = implode(chr(10), file("navigator.xsl"));$xmlstring = implode(chr(10), file("navi.xml"));$arguments = array( '/xml' => $xmlstring, '/xsl' => $xslstring);$xh = xslt_create();$result = xslt_process($xh, 'arg:/xml', 'arg:/xsl', NULL, $arguments);if ($result) { print $result;} else { print "Err";}xslt_free($xh);?>
程式先讀入 XSLT 與 XML 兩個檔案,透過 xslt_process 把 XML 依樣式表轉換後輸出。
<?xml version="1.0" encoding="GB2312"?><?xml-stylesheet type="text/xsl" href="navigator.xsl" ?><Navigation> <Navigator ID="1" AncestorID="1" Layer="0" Title="花園首頁" Childs="0" Url="default.asp" Image="images/dc.gif"/> <Navigator ID="2" AncestorID="2" Layer="0" Title="我的花園" Childs="4" Url="#" Image="default"/> <Navigator ID="3" AncestorID="2" Layer="1" Title="收藏夾" Childs="4" Url="#" Image="default"/> ...(其餘節點略,皆為 Navigator 元素,帶有 ID、AncestorID、Layer、Title、Childs、Url、Image 等屬性)...</Navigation>
每個 Navigator 節點以屬性描述一個選單項:ID 為識別碼、AncestorID 指向父節點、Layer 表示層級深度、Childs 為子項數量、Title 為文字、Url 為連結、Image 為圖示。
<?xml version="1.0" encoding="GB2312"?><xsl:stylesheet version="1.0" xmlns:xsl="https://www.w3.org/1999/XSL/Transform"> <xsl:output method="html" version="1.0" encoding="GB2312" indent="yes"/> <xsl:template match="/"> <html> <head> <title>XSLT 樹狀導覽欄</title> <link rel="stylesheet" type="text/css" href="navigator.css"/> <script src="toggle.js"></script> </head> <body> <div> <table> <tr><td><div>有座花園分類目錄</div></td></tr> <xsl:for-each select="Navigation/Navigator"> <tr> <xsl:attribute name="ID"><xsl:value-of select="@ID"/></xsl:attribute> <xsl:attribute name="Depth"><xsl:value-of select="@Layer"/></xsl:attribute> <td style="cursor:hand"> <div> <xsl:attribute name="style">padding-left:<xsl:value-of select="@Layer"/>em;</xsl:attribute> <xsl:choose> <xsl:when test="@Childs[.>0]"> <img src="images/bs.gif"> <xsl:attribute name="onclick">toggle(<xsl:value-of select="@ID"/>)</xsl:attribute></img> </xsl:when> <xsl:otherwise> <img><xsl:attribute name="src"><xsl:value-of select="@Image"/></xsl:attribute></img> </xsl:otherwise> </xsl:choose> <a> <xsl:attribute name="href"><xsl:value-of select="@Url"/></xsl:attribute> <xsl:value-of select="@Title"/></a> </div></td> </tr> </xsl:for-each> </table> </div> </body> </html> </xsl:template></xsl:stylesheet>
樣式表用 xsl:for-each 遍歷每個 Navigator 節點,依 Layer 屬性以 padding-left 做出縮排的層級感,並用 xsl:choose 判斷:有子項(Childs > 0)時顯示可點擊收合的加號圖示並綁定 toggle 函式,否則顯示該節點自己的圖示,最後產出可收合的樹狀導覽選單。