XSLT - 複数条件分岐 (xsl:choose)Advertisement書式
<xsl:choose>
<xsl:when test="条件">
条件に一致した場合の処理
</xsl:when>
<xsl:otherwise>
処理
</xsl:otherwise>
</xsl:choose>
条件に一致した場合、処理を行う。xsl:when は複数指定可能。xsl:otherwise が指定してある場合、すべての xsl:when に一致しなかったノードが処理される。比較演算子を使用する場合、実体参照か文字参照を使用する。 例
<xsl:choose>
<xsl:when test="price<=1000">
<-- (1) -->
</xsl:when>
<xsl:when test="price>=3000">
<-- (2) -->
</xsl:when>
<xsl:otherwise>
<-- (3) -->
</xsl:otherwise>
</xsl:choose>
price の値が 1000 以下の場合、(1) の処理を行う。そうでなく、price の値が 3000 以上の場合、(2) の処理を行う。(1)(2) のどちらでもない場合、(3) の処理を行う。
サンプルコード
sample.xml
<?xml version="1.0" encoding="Shift_JIS"?>
<?xml-stylesheet type="text/xsl" href="./style.xsl"?>
<document>
<book id="10">
<title>AAA</title>
<price>4000</price>
</book>
<book id="20">
<title>BBB</title>
<price>1000</price>
</book>
<book id="30">
<title>CCC</title>
<price>2000</price>
</book>
<book id="40">
<title>DDD</title>
<price>1500</price>
</book>
<book id="50">
<title>EEE</title>
<price>500</price>
</book>
</document>
style.xsl
<?xml version="1.0" encoding="Shift_JIS"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="document">
<html>
<head>
<title>XSLT</title>
</head>
<body>
<table>
<xsl:apply-templates/>
</table>
</body>
</html>
</xsl:template>
<xsl:template match="book">
<xsl:choose>
<xsl:when test="price<=1000">
<tr>
<td style="background-color:#ccc;"><xsl:value-of select="title"/></td>
<td style="background-color:#ccc;"><xsl:value-of select="price"/></td>
</tr>
</xsl:when>
<xsl:otherwise>
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="price"/></td>
</tr>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
生成されるコード
<html> <head> <title>XSLT</title> </head> <body> <table> <tr><td>AAA</td><td>4000</td></tr> <tr><td style="background-color:#ccc;">BBB</td style="background-color:#ccc;"><td>1000</td></tr> <tr><td>CCC</td><td>2000</td></tr> <tr><td>DDD</td><td>1500</td></tr> <tr><td style="background-color:#ccc;">EEE</td><td style="background-color:#ccc;">500</td></tr> </table> </body> </html> Advertisement |
ショートカット・634トップページ・このカテゴリのトップページに戻る ・634ラボ サイト検索Y!ログール |