条件与排序

XSLT 教程 · 第 4 章 · 7 次浏览

XSLT 的条件:xsl:if 和 xsl:choose(多分支);循环:xsl:for-each(也可以靠 apply-templates 递归)。

xsl:if

test 属性写 XPath 条件,满足才输出内容。

xsl:choose

when 多分支 + otherwise 默认,相当于 switch。

xsl:for-each

select 选择节点集,逐个处理,可加 sort 排序。

代码示例

<xsl:template match="/">
  <html><body>
    <h1>价格分类</h1>
    <xsl:for-each select="bookstore/book">
      <xsl:sort select="price" data-type="number" order="descending"/>
      <p>
        <xsl:value-of select="title"/>
        <xsl:choose>
          <xsl:when test="price &gt;= 40">
            <b>(高价)</b>
          </xsl:when>
          <xsl:when test="price &gt;= 30">
            <i>(中价)</i>
          </xsl:when>
          <xsl:otherwise>(低价)</xsl:otherwise>
        </xsl:choose>
        —— ¥<xsl:value-of select="price"/>
      </p>
    </xsl:for-each>
  </body></html>
</xsl:template>