为什么这个XSLT无法正常工作?

时间:2015-11-21 15:23:52

标签: xml xslt

我想从包含具有year子元素的目录元素的XML文件中提取条目。我必须提取在给定时间段之间的元素,但我找不到这样做的方法。我尝试使用if然后但是找不到正确的方法。这是我的代码,请给我一些提示。

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

1 个答案:

答案 0 :(得分:1)

XSLT中有两点需要注意

  1. xsl:when必须位于xsl:choose
  2. 必须将<运算符转义为表达式中的&lt;
  3. 所以,你当前的XSLT应该是这样的:

    <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 &lt; 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>
    

    请注意,除非您要进行多项测试,并为每项测试采取不同的操作,否则可以将测试表达式放在select语句中。

    这意味着您的XSLT也可能如下所示:

    <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 &lt; 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>
    
相关问题