XSLT <xsl:choose> 요소

定义和用法

<xsl:choose> 元素与 <xsl:when> 以及 <xsl:otherwise> 元素结合,可以表达多重条件测试。

如果没有 <xsl:when> 是 true,那么处理 <xsl:otherwise> 的内容。

xsl:when이 true가 아니고, xsl:otherwise 요소가 없으면, 어떤 내용도 생성하지 않습니다。

ヒント:간단한 조건 검사에 대해서는 <xsl:if> 요소를 대신 사용하세요.

문법

<xsl:choose>
<!-- Content:(xsl:when+,xsl:otherwise?) -->
</xsl:choose>

속성

None

예제

예제 1

CD의 가격이 10보다 높을 때, artist 열에 핑크색 배경색을 추가합니다:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <html>
  <body>
    <h2>My CD Collection</h2>
    <table border="1">
      <tr bgcolor="#9acd32">
        <th>Title</th>
        <th>Artist</th>
      </tr>
      <xsl:for-each select="catalog/cd">
      <tr>
        <td><xsl:value-of select="title"/></td>
      	<xsl:choose>
          <xsl:when test="price > 10">
            <td bgcolor="#ff00ff">
            <xsl:value-of select="artist"/></td>
          </xsl:when>
          <xsl:otherwise>
            <td><xsl:value-of select="artist"/></td>
          </xsl:otherwise>
        </xsl:choose>
      </tr>
      </xsl:for-each>
    </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

XML 파일을 확인하다, XSL 파일을 확인하다, 결과를 확인하다.

예제 2

이름이 "color"인 변수를 선언합니다. 이 변수의 값을 현재 요소의 color 속성에 할당합니다. 현재 요소에 color 속성이 없으면 color의 값은 "green"입니다:

<xsl:variable name="color">
  <xsl:choose>
    <xsl:when test="@color">
      <xsl:value-of select="@color"/>
    </xsl:when>  
    <xsl:otherwise>green</xsl:otherwise>
  </xsl:choose>
</xsl:variable>