Nic
Nic

Reputation: 43

how xpath contains() function works

I am having problems using the XPath and contains function. Imagine the XML example below:

<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>

I want to return all the films that have 'Action' in the genre attribute this is what I currently have but it is not working. Can anyone see my mistake ?

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

Any help appreciated.

<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>

It returns everything.

Upvotes: 0

Views: 729

Answers (1)

Phil
Phil

Reputation: 164767

Now that we know the context, this is quite easy. Just put the condition in your for-each selector.

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

Why bother templating nodes you'll never need? If you really want to use a test inside the loop, use this

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

Upvotes: 1

Related Questions