2011年6月21日 星期二

XSLT 筆記



PS: 這是筆記,不是詳細的教學手冊


◎ XSLT 可用於 XML 轉換成其他格式的 XML, HTML 或其他格式檔,所以,將它視為



  • 檔案格式轉換程式

  • 或,一種 Template Engine


◎ 和 DOM Tree 的處理一樣,藉由 XPath 的方式來「指定」XML 文件內的特定 element,然後進行各 element 內容的萃取以及處理,一些可以縮寫的 XPath 語法











































































非縮寫 縮寫 說明
/ / root
child:para para 目前節點下所有 para 的子點 (只有下一層)
/child:para /para root 下所有 para 的子點
descendant::para .//para 目前節點下所有 para 的子點 (不限只有下一層)
/descendant::para //para root 節點下所有 para 的子點 (不限只有下一層)
attribute::id @id 具有 id 的屬性的節點
attribute::* @* 所有屬性的節點
child::chapter[position()=5] chapter[5]
child::chapter[attribute::id="this-one"] chapter[@id="this-one"]
child::chapter[not(attribute::include="y")] child::chapter[not(@include="y")]
/descendant::text() //text() 目前節點下的所有文字節點
child::part[attribute::num="1"][attribute::draft="y"] part[@num="1"][@draft="y"]
parent::node()[attribute::include="y"] ..[@include="y"] 選擇 include 屬性內包含 "y" 的母節點
/descendent::chapter[attribute::id and attribute::include] //chapter[@id and @include]

◎ 例子: 資料檔假設 data.xml


<?xml version="1.0"?>
<Position>
<X>9</X>
<Y>9</Y>
</Position>
<Position>
<X>10</X>
<Y>9</Y>
</Position>

我們可以撰寫一個 xsl 檔,假設為 extract.xsl


 
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>

<xsl:template match="Position">
<xsl:value-of select="./X" />
<xsl:text>,</xsl:text>
<xsl:value-of select="./Y" />
</xsl:template>

</xsl:stylesheet>

然後,我們可以抓個 XSLT Processor,比如 Saxon ,執行


 
java -jar saxon.jar data.xml convert.xsl

就會產生


 
9,9
10,9

的結果


◎ 當然,有其他更複雜的操作方式,略記一些常用的語法



  • xsl:apply-templates 整個 XSLT 的核心語法

  • xsl:template

  • xsl:value-of select=xxx 將結果輸出

  • xsl:import href=xxx 可以 reuse 其他 xsl 檔

  • xsl:include 同前者,唯相同定義出現,這個會中止 compile.

  • xsl:strip-space xsl:preserve-space 處理空白

  • xsl:output

  • xsl:key

  • xsl:decimal-format 用來設定數字的格式

  • xsl:namespace-alias

  • xsl:attribute-set 設定屬性組

  • xsl:variable xsl:param 處理一些變數運算

  • 條件式判斷

    • xsl: if test="xxx=1"

    • xsl:choose xsl:when




◎ Saxon 是 for Java, 若要 C/C++ 版本,可以考慮



  • Xalan

  • Sablontron (with expat XML processor)


◎ MacOSX 下用 MacPort 安裝


 
sudo port install saxon

安裝在 /opt/local/var/macports/software/saxon/8.9_0 目錄,可以在 .profile 內加下述這行,以簡化指令執行


 
alias saxon='java -jar /opt/local/var/macports/software/saxon/8.9_0/opt/local/share/java/saxon8.jar'

但要注意 saxon8 支援 XSLT2.0,所以,可能執行時會出現下述訊息


 
Running an XSLT 1.0 stylesheet with an XSLT 2.0 processor

只要在 xsl:stylesheet version 的部份由原 1.0 改成 2.0 即可 pass 該訊息。


◎ 參考:



 



reference : http://blog.derjohng.com/2008/10/16/xslt-%E7%AD%86%E8%A8%98/

沒有留言:

wibiya widget