<xsl:choose>、<xsl:when>、<xsl:otherwise>を使って複数の条件で処理を分ける

<xsl:choose>、<xsl:when>、<xsl:otherwise>の使い方がポイント。 JavaScriptで言えば、if〜else文みたいなもの。 社員要素のテンプレートでは、コンテキストノードが社員要素なので、 そのテキスト内容をtext()で取り出している。 ここをピリオド(.)にしても結果は同じになる。
【sample021.xml】
<?xml version="1.0" encoding="Shift_JIS" ?>
<?xml-stylesheet href="sample021.xsl" type="text/xsl" ?>
<社員名簿>
<社員 社員番号="001" 性別="男" 役職="社長">山田太郎</社員>
<社員 社員番号="002" 性別="男" 役職="取締役">鈴木健一</社員>
<社員 社員番号="003" 性別="女" 役職="取締役">菊池桃子</社員>
<社員 社員番号="004" 性別="男" 役職="部長">吉田啓介</社員>
<社員 社員番号="005" 性別="女" 役職="部長">三好恵美子</社員>
<社員 社員番号="006" 性別="男" 役職="">神田紀夫</社員>
<社員 社員番号="007" 性別="男" 役職="">菊野浩二</社員>
<社員 社員番号="008" 性別="女" 役職="">美濃励子</社員>
<社員 社員番号="009" 性別="男" 役職="">岡野祐輔</社員>
<社員 社員番号="010" 性別="男" 役職="">和田真一</社員>
</社員名簿>


【sample021.xsl】
<?xml version="1.0" encoding="Shift_JIS" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="Shift_JIS" />

<xsl:template match="社員名簿">
	<html>
	<head><title>複数条件の分岐処理</title></head>
	<body>
	<h2><xsl:choose>、<xsl:when>、<xsl:otherwise>を使って複数の条件で処理を分ける</h2>
	<p><xsl:apply-templates /></p>
	</body>
	</html>
</xsl:template>

<xsl:template match="社員">
	<xsl:choose>
		<xsl:when test="@役職='社長'">
		<p>社長は<xsl:value-of select="text()"/>さんです。</p>
		</xsl:when>
		<xsl:when test="@役職='取締役'">
		<p>取締役は<xsl:value-of select="text()"/>さんです。</p>
		</xsl:when>
		<xsl:when test="@役職='部長'">
		<p>部長は<xsl:value-of select="text()"/>さんです。</p>
		</xsl:when>
		<xsl:otherwise>
		<p>平社員は<xsl:value-of select="text()"/>さんです。</p>
		</xsl:otherwise>
	</xsl:choose>
</xsl:template>

</xsl:stylesheet>


【結果】