4. 様々な条件処理
XSLT 4章 様々な条件処理
- 4.1 繰り返し
- 4.2 xsl:if を用いた条件付き処理
- 4.3 xsl:choose を用いた条件付き処理
- 4.4 ソート
この章においては、以下の XML 文書を用いて様々な条件処理についてみていきたいと思います。
4.1 繰り返し
<xsl:for-each select = node-set-expression> <!-- Content: (xsl:sort*, template) --> </xsl:for-each>
結果が規則性のある構造を持つことが分かっている場合には、選択したノードに直接テンプレートを指定できると便利です。xsl:for-each 要素は、必須である select 属性によって指定されたノードに対して繰り返しテンプレートを適用します。
select 属性には、繰り返し処理を行うノードを特定する XPath 式でノード集合を指定します。
<xsl:template match="people/person">
*** <xsl:value-of select="name"/> ***
<xsl:for-each select="work">
<xsl:value-of select="."/>,
</xsl:for-each>
</xsl:template>
上記のテンプレートを people.xml に適用すると以下の出力を得られます。
*** Kevin Shields ***
isn't anything,
loveless,
*** Trent Reznor ***
pretty hate machine,
broken,
the downward spiral,
the fragile,
and all that could have been,
4.2 xsl:if を用いた条件付き処理
<xsl:if test = boolean-expression> <!-- Content: template --> </xsl:if>
xsl:if 要素は、単純な if-then (〜なら〜を実行する) 型の条件処理を行います。test 属性は必須で、属性値として XPath の式を指定します。式を評価した結果が true の場合はテンプレートを適用し、それ以外の場合は何も生成しません。
<xsl:template match="people/person">
*** <xsl:value-of select="name"/> ***
<xsl:for-each select="work">
<xsl:if test="position()=last()">
<xsl:value-of select="."/>
</xsl:if>
</xsl:for-each>
</xsl:template>
上記のテンプレートを people.xml に適用すると以下の出力を得られます。
*** Kevin Shields ***
loveless
*** Trent Reznor ***
and all that could have been

