2012-10-23 51 views
1

之前從未做過XSLT。有可能繼承文檔並只替換一個標籤嗎?如果是的話,你能提供任何例子嗎?XSLT繼承。替換HTML標籤?

謝謝

+0

需要一些更多的信息 –

+0

是的,有如何做到這一點的SO和其他很多很多的例子。該要查找的關鍵概念是_identity template_ - 低優先級模板e只是將其輸入複製到輸出不變,然後您可以使用更具體的模板覆蓋任何要處理的內容。 –

+0

代碼示例?我可以標記單個​​標記並在子xslt文檔中覆蓋它嗎?或者我必須重複一個結構?伊恩,任何鏈接? – Sergejs

回答

3

你開始

<xsl:template match="@* | node()"> 
    <xsl:copy> 
    <xsl:apply-templates select="@* | node()"/> 
    </xsl:copy> 
</xsl:template> 

然後添加模板轉換的節點模板要變換例如

<xsl:template match="td"> 
    <th> 
    <xsl:apply-templates select="@* | node()"/> 
    </th> 
<xsl:template> 

變換所有td元素注入th元件或

<xsl:template match="h6"/> 

刪除所有h6元素。

如果你想改變一個td那麼你需要一些方法來識別它,假設它有一個id屬性使用匹配模式像

<xsl:template match="td[@id = 'td1']"> 
    <td style="background-color: lightgreen;"> 
    <xsl:apply-templates select="@* | node()"/> 
    </td> 
</xsl:template> 

這樣設置特定td的CSS background-color財產元件。

0

這個任務最好最根本的XSLT設計模式進行處理:使用和重寫identity rule

讓我們有這個XML文檔:

<root> 
    <x>This is:</x> 
    <a> 
     <b> 
     <c>hello</c> 
     </b> 
    </a> 
    <a> 
     <b> 
     <c1>world</c1> 
     </b> 
    </a> 
    <a> 
     <b>!</b> 
    </a> 
    <y>The End</y> 
</root> 

任務是

  1. 全部刪除c個元素。

  2. 將任何b元素重命名爲d

  3. 在任何c1元素後插入c2元素。

的解決方案是令人驚訝的簡短

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output omit-xml-declaration="yes" indent="yes"/> 
<xsl:strip-space elements="*"/> 

<xsl:template match="node()|@*" name="identity"> 
    <xsl:copy> 
     <xsl:apply-templates select="node()|@*"/> 
    </xsl:copy> 
</xsl:template> 

<xsl:template match="c"/> 

<xsl:template match="b"> 
    <d><xsl:apply-templates select="node()|@*"/></d> 
</xsl:template> 

<xsl:template match="c1"> 
    <xsl:call-template name="identity"/> 
    <c2>xxx</c2> 
</xsl:template> 
</xsl:stylesheet> 

當該變換是在上面的XML文檔應用,有用的,正確的結果產生

<root> 
    <x>This is:</x> 
    <a> 
     <d/> 
    </a> 
    <a> 
     <d> 
     <c1>world</c1> 
     <c2>xxx</c2> 
     </d> 
    </a> 
    <a> 
     <d>!</d> 
    </a> 
    <y>The End</y> 
</root> 

說明

  1. 當選擇執行或按名稱調用時,標識模板將「按原樣」複製當前節點。

  2. 對於每一個特殊的任務(刪除,插入和重命名,我們添加符合要求的節點,從而覆蓋了身份模板一個單獨的模板,因爲較高的特異性。

  3. 壓倒一切的,更具體的模板選擇了它相匹配,並且在節點上執行performes,我們需要執行該任務。