2012-07-30 62 views
2

我有一個XML文件,比方說: 重寫的for-each XSLT

<parent> 
    <notimportant1> 
    </notimportant1>.  
    <notimportant2> 
    </notimportant2>. 
    .... 
    <child> 
     <grandchild>. 
           .... 
        </grandchild> 
        <grandchild> 
           .... 
        </grandchild>. 
         .... 
        <notimportant3> 
        </notimportant3> 
    </child> 
<parent> 
  

而且有XSL文件:

<xsl:template match="parent">. 
     ... 
     ... 
    <xsl:for-each select="child">.  
      <xsl:for-each select="grandchild"> 
          ... 
         </xsl:for-each>.  
     </xsl:for-each> 
      .... 
</xsl:template> 

現在,我要創建新的xsl文件, 這隻能導入/包含這個現有的xsl

是否有可能重寫此爲每個行爲,以便取代它我只能顯示一些預定義的文本/鏈接?

我無法修改現有的xsl,我想使用模板中的所有內容 - 不能僅僅定義具有更高優先級的新項。

回答

2

這裏的策略是定義一個匹配parent的第二個模板,以確保導入的模塊永不運行(因爲您無法更改導入的模板,也不會在匹配後禁止它的行爲)。

默認情況下,導入的模板的優先級低於本地優先級,因此只需定義另一個模板即可解決此問題。

您還可以通過給予模板priority屬性來控制優先級。它越高,匹配節點集越有可能(意味着低優先級不會)。

模板模式也是一個選項,但我認爲你已經足夠在這裏繼續。

XML Transforms - xsl:template (priority)

XSLT Element

+2

打倒我,大約5秒鐘。 – 2012-07-30 13:10:14

+0

哈哈,它通常是相反的方向 – Utkanos 2012-07-30 13:10:33

+0

問題是,我想使用模板中的所有內容,因此我無法覆蓋整個模板。 – user1562977 2012-07-30 13:18:40

5

你可以重新設計你原來的樣式表使用xsl:apply-templates,而不是xsl:for-each。事情是這樣的:

<xsl:template match="parent"> 
    ... 
    ... 
    <xsl:apply-templates select="child"/> 
    .... 
</xsl:template> 

<xsl:template match="child"> 
    <xsl:apply-templates select="grandchild"/>  
</xsl:template> 

<xsl:template match="grandchild"> 
    ... 
</xsl:template> 

然後,當你在導入另一個樣式表,你可以重寫模板匹配childgrandchild如你所願。

+0

是的。人們常常難以解釋爲什麼人們應該使用應用程序模板而不是每個應用程序模板,並且可覆蓋性是最實際的好處之一。 – 2012-07-30 16:29:10