2013-04-02 64 views
0

XML元素我有下面的XML存儲的電影和演員:XSLT - 超鏈接基於其屬性

<movies 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:noNamespaceSchemaLocation="movies.xsd"> 

<movie movieID="1"> 
    <cast> 
     <actors> 
      <actor actorID="1"> 
       <name>Bob</name> 
      </actor> 
      <actor actorID="2"> 
       <name>John</name> 
      </actor> 
      <actor> 
       <name>Mike</name> 
      </actor> 
     </actors> 
    </cast> 
</movie> 

</movies> 

前兩個演員有一個屬性「的actorId」具有獨特的價值。第三個演員沒有屬性。 我想將前兩名演員的姓名顯示爲超鏈接,並將第三名演員姓名顯示爲純文本。

這是我的XSLT:

<xsl:template match="/"> 
    <xsl:apply-templates select="movies/movie" /> 
</xsl:template> 

<xsl:template match="movie">  
    <xsl:text>Actors: </xsl:text> 
    <xsl:apply-templates select="cast/actors/actor[@actorID]/name"/> 
</xsl:template> 

<xsl:template match="actor[@actorID]/name"> 
    <xsl:element name="a"> 
     <xsl:attribute name="href">www.mywebsite.com</xsl:attribute> 
     <xsl:value-of select="." /> 
    </xsl:element> 
    <xsl:element name="br" /> 
</xsl:template> 

<xsl:template match="actor/name"> 
    <xsl:value-of select="." /> 
    <xsl:element name="br" /> 
</xsl:template> 

,我得到的是鮑勃和約翰顯示爲純文本,和Mike根本不顯示輸出。所以它幾乎與我想要實現的 相反。

回答

2

你的XPath位置:

<xsl:apply-templates select="cast/actors/actor[@actorID]/name"/> 

導致模板只適用於具有一個actorID屬性演員。相反,它聽起來像這是你應該使用什麼:

<xsl:apply-templates select="cast/actors/actor/name"/> 

那麼XSLT的行爲應該像你期望的那樣。

作爲一個方面說明,我會建議你使用XSLT文字元素,除非有必要使用xsl:element

<xsl:template match="actor[@actorID]/name"> 
    <a href="http://www.mywebsite.com"> 
     <xsl:value-of select="." /> 
    </a> 
    <br /> 
</xsl:template> 

<xsl:template match="actor/name"> 
    <xsl:value-of select="." /> 
    <br /> 
</xsl:template> 

它使XSLT更易於閱讀恕我直言。如果需要在屬性中包含值,則可以使用屬性值模板:

<a href="http://www.mywebsite.com/actors?id={../@actorID}"> 
+0

謝謝您的回覆,JLRishe。我已將您的解決方案應用於我的代碼,現在Bob,John和Mike顯示爲純文本。看起來第二個模板匹配覆蓋了第一個。 – Alex

+1

您是否修改了這一行:''?那個應該保持不變,只是'apply-templates'應該被修改了。如果你只修改了'apply-templates',第二個模板仍然覆蓋第一個模板,你可以嘗試在第一個模板中添加一個優先級屬性:'' – JLRishe

+0

優先級屬性完成了這項工作。這顯示了在xslt中解決問題有多少種方法。一如既往,非常感謝你的幫助,JLRishe。 – Alex