简体   繁体   中英

Counting a subset in xslt

I got a simple xml about movies it follows like this:

 <movies> <!-- 1 --> <movie> <movieID>0108052</movieID> <title>Schindler's List</title> <director>Steven Spielberg</director> <year>1993</year> <genre>Biography, Drama, History</genre> <link>http://www.imdb.com/title/tt0108052/</link> </movie> <!-- 2 --> <movie> <movieID>0914798</movieID> <title>The Boy in the Striped Pajamas</title> <director>Mark Herman</director> <year>2008</year> <genre>Drama, War, History</genre> <link>http://www.imdb.com/title/tt0914798/</link> </movie> </movies> 

Now I got some tables made depending on which year the movies fall on. And at the end I wanted to add an extra footer row saying how many movies were made on that year. I used this code:

 <td>Number of Movies: <xsl:value-of select="count(movies/movie)"/> </td> 

But that only gives me all the movies in the xml, Is there any way I can limit it to movies done in say after 2004? I was thinking to perhaps count the number rows in the table if that is possible and performing arithmetic, but I don't know if xslt can do that.

I create the tables using this:

 <xsl:for-each select="movies/movie"> <!-- Sort by title --> <xsl:sort select="title"/> <xsl:if test="year>=2005"> <tr bgcolor="#3D9999"> <td> <!-- Look for link, target to blank, the link text is the tittle pulled from xml --> <a href="{link}" target="_blank"><xsl:value-of select="title"/></a> </td> <td> <xsl:value-of select="director"/> </td> <td> <xsl:value-of select="year"/> </td> <td> <xsl:value-of select="genre"/> </td> <td> <xsl:value-of select="movieID"/> </td> </tr> </xsl:if> </xsl:for-each> 

You can filter the expression to count a subset like so:

<xsl:value-of select="count(movies/movie[year>=2005])"/>

Outputting the number of movies per year can be done by grouping using the key function for XSLT 1.0:

<?xml version="1.0"?>

<xsl:stylesheet
  version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
   <xsl:output method="html" indent="yes"/>

  <xsl:key name="movie_year" match="movie" use="year" />

  <xsl:template match="movies">
    <table>
      <tr>
        <th>Year</th>
        <th># movies</th>
      </tr>
      <xsl:for-each select="movie[generate-id(.)=generate-id(key('movie_year', year))]">
        <xsl:variable name='this' select="."/>
        <tr>
          <td><xsl:value-of select="year"/></td>
          <td><xsl:value-of select="count(../movie[year=$this/year])"/></td>
        </tr>
      </xsl:for-each>
    </table>
  </xsl:template>

</xsl:stylesheet>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM