萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

XSLT 作為 HTML 樣式表:擴充 XHTML、指令處理、跨文檔引用、客戶端與伺服器端編譯差異

XSLT 樣式表定位

XSLT 不僅用於 XML 轉換,亦可**擴充 XHTML 文檔**。輸入輸出命名空間相同(HTML),大部分標記原樣複製,僅擴充特定指令(如腳註、模組、目錄生成)。**補充而非替代 CSS**——CSS 處理字體/顏色/間距,XSLT 處理內容組合與結構生成。

必要基礎代碼

<s:stylesheet
  xmlns="https://www.w3.org/1999/xhtml"
  xmlns:h="https://www.w3.org/1999/xhtml"
  xmlns:s="https://www.w3.org/1999/XSL/Transform"
  exclude-result-prefixes="a h"
  version="1.0">
  <s:template match="h:head">
    <s:copy>
      <s:apply-templates select="@*|node()"/>
      <meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
      <link href="common.css" rel="stylesheet" type="text/css"/>
    </s:copy>
  </s:template>
  <s:template match="*">
    <s:copy>
      <s:copy-of select="@*"/>
      <s:apply-templates/>
    </s:copy>
  </s:template>
</s:stylesheet>
  • 預設命名空間寫輸出 XHTML,h: 用於 XPath 匹配。
  • match="head" 擴充 head 區(引入 CSS、設定編碼)。
  • match="*" 深度複製所有節點(含屬性),避免只輸出文字內容。

擴充範例:內部連結加上方向箭頭

<s:stylesheet ...>
  <s:import href="common.xsl"/>
  <s:template match="h:a[starts-with(@href,'#')]">
    <s:copy>
      <s:copy-of select="@*"/>
      <s:variable name="name" select="substring-after(@href,'#')"/>
      <s:choose>
        <s:when test="preceding::h:a[@name=$name]"><s:text>^</s:text></s:when>
        <s:otherwise><s:text>v</s:text></s:otherwise>
      </s:choose>
      <s:apply-templates/>
    </s:copy>
  </s:template>
</s:stylesheet>

邏輯:錨點連結若目標在前面顯示 ^,在後面顯示 v。

其他應用場景

  • 引用外部文檔片段(document() 函數)
  • 自動生成目錄(遞迴處理標題層級)
  • 腳註/端註自動編號與雙向連結

客戶端 vs 伺服器端執行

  • 瀏覽器支援 XSLT 1.0,但 **XSLT 2.0(XPath 2.0、分組、自訂函數)需伺服器端執行**。
  • 伺服器端編譯可輸出純 HTML,相容性最佳、效能最穩定。
copyright © 萬盛學電腦網 all rights reserved