2013-12-24 97 views
0

我在使用XPath和包含函數時遇到問題。試想一下,下面的XML例子:xpath包含()函數的工作方式

<movie-selection> 
<film> 
    <name>Hunger Games - Catching Fire</name> 
    <release>2013</release> 
    <description>Katniss Everdeen and Peeta Mellark are once again forced to fight for there lifes in the Hunger Games. There Victory the previous year kick starts a rebellion againist the Capitol and President Snow. 
    </description> 
    <runtime>146 minutes</runtime> 
    <stars>Jennifer Lawrence, Josh Hutcherson, Liam Hemsworth</stars> 
    <genre>Adventure, Sci-Fi</genre>   
<rating>4.8</rating> </film> 

<film> 
    <name>Avatar</name> 
    <release>2009</release> 
    <description>A paraplegic Marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home. 
    </description> 
    <runtime>162 minutes</runtime> 
    <stars> Sam Worthington, Zoe Saldana, Sigourney Weaver</stars> 
    <genre>Adventure, Fantasy, Action</genre> 
    <rating>4.5</rating> 

我想回到那個有「行動」在類型屬性這所有的電影是什麼,我現在有,但它是不是加工。任何人都能看到我的錯誤?

movie-selection/film[contains(genre, 'Action')] 

任何幫助表示讚賞。

<xsl:for-each select="movie-selection/film"> 
    <xsl:if test="/movie-selection/film[contains(genre, &apos;Drama&apos;)]"> 
     <p><xsl:value-of select="name"/></p> 
     <p><xsl:value-of select="release"/></p> 
     <p><xsl:value-of select="runtime"/></p> 
     <p><xsl:value-of select="description"/></p> 
     <p><xsl:value-of select="stars"/></p> 
     <p><xsl:value-of select="genre"/></p> 
     <p><xsl:value-of select="rating"/></p> 
    </xsl:if> 
</xsl:for-each> 

它返回一切。

+1

在你的榜樣,1)'genre'不是一個屬性,但是一個元素2)沒有'genre'包含的行動值」。 – BoltClock

+0

我只看到缺少的是一個主要的斜線,例如'/ movie-selection/film [contains(genre,'Action')]''。將其更改爲* Adventure *並獲得一個匹配,請參閱http://www.xpathtester.com/obj/65cee161-dbc1-46a3-a29a-ab1b4360fee9 – Phil

+0

它似乎在路徑測試程序中正常工作而不是xsl文件 – Nic

回答

1

現在我們知道上下文,這很容易。只需將條件放入for-each選擇器即可。

<xsl:for-each select="movie-selection/film[contains(genre, 'Drama')]"> 
    <p><xsl:value-of select="name" /></p> 
    <!-- and so on --> 
</xsl:for-each> 

爲什麼打擾你永遠不需要的模板節點?如果你真的想用一個測試循環內,使用該

<xsl:for-each select="movie-selection/film"> 
    <xsl:if test="contains(genre, 'Drama')"> 
+0

謝謝。我對XML的工作非常陌生,儘管Dreamweaver仍然在學習很多東西。 – Nic

+0

您的代碼不起作用的原因是,以「/」開頭的路徑搜索整個文檔,而您想要在當前正在處理的元素(稱爲「上下文節點」)內搜索。 –

+0

@MichaelKay我認爲你評論了錯誤的帖子。我的代碼工作正常 – Phil