Element <xsl:if> XSLT

Definicja i użycie

<xsl:if> zawiera szablon, który jest stosowany tylko wtedy, gdy spełniony jest określony warunek.

Wskazówka: Użyj <xsl:choose> z <xsl:when> i <xsl:otherwise>, aby wyrazić wielokrotne testy warunkowe!

gramatyka

<xsl:if
test="wyrażenie">
<!-- Content: template -->
</xsl:if>

atrybut

atrybut wartość opis
test wyrażenie Wymagane. Określa warunek do sprawdzenia.

Przykład

Przykład 1

Kiedy cena CD jest wyższa niż 10, wybierz wartości title i 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>Moja kolekcja płyt CD</h2>
    <table border="1">
      <tr bgcolor="#9acd32">
        <th>Tytuł</th>
        <th>Artysta</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>

Zobacz plik XML,Zobacz plik XSL,Zobacz wynik.

Przykład 2

Wyświetl tytuły każdego CD. Jeśli nie jest ostatnim lub przedostatnim CD, wstaw ", " między tytułami CD. Jeśli jest ostatnim CD, dodaj "!" po tytule. Jeśli jest przedostatnim CD, dodaj ", and " po nim:

<?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>Moja kolekcja płyt CD</h2>
    <p>Tytuły:
    <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> i </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>