XSLT <xsl:if> 要素
定義と用法
<xsl:if>にはテンプレートが含まれており、指定された条件が成立した場合にのみ、このテンプレートが適用されます。
ヒント:<xsl:choose>と<xsl:when>および<xsl:otherwise>を組み合わせて、複数の条件テストを表現してください!
文法
<xsl:if test="expression"> <!-- Content: template --> </xsl:if>
属性
属性 | 値 | 説明 |
---|---|---|
test | expression | 必須。テストする条件を指定します。 |
例
例1
CDの価格が10より高い場合、titleと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>私のCDコレクション</h2> <table border="1"> <tr bgcolor="#9acd32"> <th>Title</th> <th>Artist</th> </tr> <xsl:for-each select="catalog/cd"> <xsl:if test="price > 10"> <tr> <td><xsl:value-of select="title"/></td> <td><xsl:value-of select="artist"/></td> </tr> </xsl:if> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>
例2
各CDのタイトルを表示します。最後のCDでない場合、各CDタイトル間に「, 」を挿入します。最後のCDの場合、タイトルの後に「!」を追加します。最後の2番目のCDの場合、その後に「, and 」を追加します:
<?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>私のCDコレクション</h2> <p>タイトル:</p> <xsl:for-each select="catalog/cd"> <xsl:value-of select="title"/> <xsl:if test="position()!=last()"> <xsl:text>, </xsl:text> </xsl:if> <xsl:if test="position()=last()-1"> <xsl:text> and </xsl:text> </xsl:if> <xsl:if test="position()=last()"> <xsl:text>!</xsl:text> </xsl:if> </xsl:for-each> </p> </body> </html> </xsl:template> </xsl:stylesheet>