跟我学XSL(五)

[入库:2005年8月18日] [更新:2007年3月25日]

本文简介:选择自 ghj1976 的 blog

  上期我们学习了xsl元素< xsl:if >,已能通过测试xml数据的值来决定不同的输出形式(不知你尝试过没有,实际上< xsl:for-each >也可部分实现< xsl:if >的功能),但有时,我们希望对同一数据同时测试多个条件,根据不同条件输出相应结果。当然,我们可以用if,假如我们只有if可用的话。幸好我们有一个更好的选择,那就是用< xsl:choose >。下面介绍相关元素的语法:

< xsl:choose >
语法:< xsl:choose >
属性:无,表示一个多选测试的开始

< xsl:when >
语法:
< xsl:when expr="script-expression" language="language-name" test="pattern" >
属性:
expr ── 脚本语言表达式,计算结果为“真”或“假”;如果结果为“真”,且通过test,则在输出中显示其中内容(可省略此项属性)。
language ── expr属性中表达式的脚本语言类型,其取值与html标记script的language属性的取值相同,缺省为“jscript”。
test ── 源数据测试条件。

< xsl:otherwise >
语法:< xsl:otherwise >
属性:无,在一个多选测试中,如果没有不满足< xsl:when >规定的条件,如果在最后有此标记,则输出此标记中的内容。

示例:

  此处以学生成绩单为例,要求按成绩的高低给出优秀( >85)、一般(70~85)、起格(60~69)、不及格(< 60),而不是显示分数。其中成绩单的xml文档(文件名:grade.xml)如下:
< ?xml version="1.0" encoding="gb2312"? >
< ?xml:stylesheet type="text/xsl" href="grade.xsl"? >
< document >
< grade >
< name >大胖< /name >< english >80< /english >
< math >90< /math >< chymest >90< /chymest >
< /grade >
< grade >
< name >小花< /name >< english >98< /english >
< math >70< /math >< chymest >85< /chymest >
< /grade >
< /document >
  为实现按分数分等级显示,其xsl文档(文件名:grade.xsl)内容如下:
< ?xml version="1.0" encoding="gb2312"? >
< xsl:stylesheet xmlns:xsl="http://www.w3.org/tr/wd-xsl" >
< xsl:template match="/" >
< html >
< head >< title >成绩单< /title >< /head >
< body >< xsl:apply-templates select="document"/ >< /body >
< /html >
< /xsl:template >
< xsl:template match="document" >
< table border="1" cellspacing="0" >
< th >姓名< /th > < th >英语< /th >< th >数学< /th >< th >化学< /th >
< xsl:apply-templates select="grade"/ >
< /table >
< /xsl:template >
< xsl:template match="grade" >
< tr >
< td >< xsl:apply-templates select="name"/ >< /td >
< td >< xsl:apply-templates select="english"/ >< /td >
< td >< xsl:apply-templates select="math"/ >< /td >
< td >< xsl:apply-templates select="chymest"/ >< /td >
< /tr >
< /xsl:template >
< xsl:template match="name" >< xsl:value-of/ >< /xsl:template >
< xsl:template match="english|math|chymest" >
< xsl:choose >
< xsl:when test=".[value() $gt$ 85]" >优秀< /xsl:when >
< xsl:when test=".[value() $gt$ 70]" >一般< /xsl:when >
< xsl:when test=".[value() $gt$ 60]" >起格< /xsl:when >
< xsl:otherwise >不起格< /xsl:otherwise >
< /xsl:choose >
< /xsl:template >
< /xsl:stylesheet >
说明:
  在< xsl:choose >选择中,从第一个< xsl:when >开始,逐个测试,直到满足一个测试条件就将其中的内容输出,不再测试后面的条件;如果不满足任何一个条件,则输出< xsl:otherwise >中的内容。
  标记对< xsl:when >< /xsl:when >与< xsl:otherwise >< /xsl:otherwise >中可嵌套< xsl:if >或< xsl:choose >。

本文关键:跟我学XSL(五)
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top