XSLT条件选择全解析

发布时间:2026/6/5 15:07:09

XSLT条件选择全解析 XSLTchoose元素详解XSLT 中的choose元素是一种条件判断结构类似于编程语言中的switch-case语句。它通常与when和otherwise子元素结合使用用于根据不同的条件执行不同的逻辑。基本语法结构xsl:choose xsl:when test条件表达式1 !-- 逻辑1 -- /xsl:when xsl:when test条件表达式2 !-- 逻辑2 -- /xsl:when xsl:otherwise !-- 默认逻辑 -- /xsl:otherwise /xsl:choose代码实例解析实例1根据分数评级以下示例根据输入的分数输出对应的评级xsl:template match/ xsl:variable namescore select85/ xsl:choose xsl:when test$score 90 gradeA/grade /xsl:when xsl:when test$score 80 gradeB/grade /xsl:when xsl:when test$score 70 gradeC/grade /xsl:when xsl:otherwise gradeD/grade /xsl:otherwise /xsl:choose /xsl:template输出结果gradeB/grade实例2处理XML节点数据假设有以下XML数据books book categoryfictionThe Great Gatsby/book book categorynon-fictionSapiens/book book categoryfiction1984/book /books使用choose处理不同类别的书籍xsl:template matchbook xsl:choose xsl:when testcategoryfiction fiction_book xsl:value-of select./ /fiction_book /xsl:when xsl:when testcategorynon-fiction non_fiction_book xsl:value-of select./ /non_fiction_book /xsl:when xsl:otherwise other_book xsl:value-of select./ /other_book /xsl:otherwise /xsl:choose /xsl:template输出结果fiction_bookThe Great Gatsby/fiction_book non_fiction_bookSapiens/non_fiction_book fiction_book1984/fiction_book实例3多重条件判断when元素支持复杂的条件表达式xsl:template matchproduct xsl:choose xsl:when testprice 100 and stock 0 statuspremium_available/status /xsl:when xsl:when testprice 100 and stock 0 statusstandard_available/status /xsl:when xsl:otherwise statusout_of_stock/status /xsl:otherwise /xsl:choose /xsl:template注意事项choose结构会按顺序评估when条件第一个满足条件的分支会被执行后续分支不再评估。otherwise是可选的但若存在则必须放在最后。条件表达式中的比较运算符包括,!,,,,。使用and、or可以组合多个条件。高级应用示例实例4结合XPath函数xsl:template matchemployee xsl:choose xsl:when teststarts-with(name, A) groupA/group /xsl:when xsl:when testcontains(department, Sales) groupSales/group /xsl:when xsl:otherwise groupOther/group /xsl:otherwise /xsl:choose /xsl:template实例5嵌套choose结构xsl:template matchorder xsl:choose xsl:when testpriorityhigh xsl:choose xsl:when testpaymentcredit processexpress_credit/process /xsl:when xsl:otherwise processexpress_cash/process /xsl:otherwise /xsl:choose /xsl:when xsl:otherwise processstandard/process /xsl:otherwise /xsl:choose /xsl:template性能优化建议将最可能匹配的条件放在前面。避免过度嵌套choose结构。复杂条件考虑使用if或模式匹配替代。

相关新闻