Reputation: 87
I would like to extract the entries from an XML file with catalog elements which has a year child element. I have to extract the elements which are between a given time period but I can't find a way to do this. I tried with if's and then but couldn't find the right way to do it. Here is my code, please give me some tips.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>Bibliography entries</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Type</th>
<th>Year</th>
</tr>
<xsl:for-each select="catalog/cd">
<xsl:when test="(year > 2000) and (year < 2005)">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="type"/></td>
<td><xsl:value-of select="year"/></td>
</tr>
</xsl:when>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Upvotes: 0
Views: 293
Reputation: 70598
There are two things to note in your XSLT
xsl:when
must be inside an xsl:choose
<
operator must be escaped as <
inside an expression.So, you current XSLT should look like this:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>Bibliography entries</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Type</th>
<th>Year</th>
</tr>
<xsl:for-each select="catalog/cd">
<xsl:choose>
<xsl:when test="(year > 2000) and (year < 2005)">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="type"/></td>
<td><xsl:value-of select="year"/></td>
</tr>
</xsl:when>
</xsl:choose>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Note that unless you are going to have multiple tests, and take differing actions for each test, you can put your test expression in the select statement.
This means your XSLT can also look like this:
<xsl:template match="/">
<html>
<body>
<h2>Bibliography entries</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Type</th>
<th>Year</th>
</tr>
<xsl:for-each select="catalog/cd[year > 2000 and year < 2005]">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="type"/></td>
<td><xsl:value-of select="year"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Upvotes: 1