XML technologies / XSLT / Java and XSLT / XSLT – Advanced techniques / Conditional processing

(Excerpt from “Java und XSLT” by Eric M. Burke)

The following template, shown in example Loops and sorting, lines 95–103, prints federal presidents’ names. It outputs first name, surname and any middle initial, separated by nonbreaking spaces. Some presidents have no middle name, so the template currently outputs two spaces between first name and surname. Correct this by checking for a middle name before outputting it and its space. This uses conditional logic, a feature present in almost every programming language.

Example: Loops and sorting

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html"/>
  <xsl:template match="/">
    <html>
      <body>
        <h1>Sortierbeispiele</h1>
        <xsl:apply-templates select="bundespraesidenten"/>
      </body>
    </html>
  </xsl:template>
  <!--********************************************************************
    ** Bundespräsidenten-Template
    *****************************************************************-->
  <xsl:template match="bundespraesidenten">
    <!--*****************************************************************
      ** Sortierung mit xsl:for-each
      **************************************************************-->
    <h2>Alle Bundespr&auml;sidenten mit xsl:for-each nach Vorname sortiert</h2>
    <xsl:for-each select="bundespraesident">
      <xsl:sort select="name/vorname"/>
      <xsl:apply-templates select="name"/>
    </xsl:for-each>
    <!--*****************************************************************
      ** Sortierung mit xsl:apply-templates
      **************************************************************-->
    <h2>Alle Bundespr&auml;sidenten mit xsl:apply-templates nach Vorname sortiert</h2>
    <xsl:apply-templates select="bundespraesident/name">
      <xsl:sort select="vorname"/>
    </xsl:apply-templates>
    <h2>Alle Bundespr&auml;sidenten mit xsl:apply-templates nach Amtszeit</h2>
    <xsl:apply-templates select="bundespraesident/name">
      <xsl:sort select="../amtsperiode/@von" data-type="number" order="descending"/>
    </xsl:apply-templates>
    <!--*****************************************************************
      ** Sortierung über mehrere Felder
      **************************************************************-->
    <h2>Beispiel zur Sortierung &uuml;ber mehrere Felder</h2>
    <xsl:apply-templates select="bundespraesident/name">
      <xsl:sort select="nachname"/>
      <xsl:sort select="vorname" order="descending"/>
    </xsl:apply-templates>
    <!--*****************************************************************
      ** Verschachtelte xsl:for-each-Schleifen
      ** (unter der Annahme, daß ein Bundespräsident Vorname, Mittelinitial
      ** und Name hat und ggf. vom Bundesratspräsidenten vertreten wird ...)
      **************************************************************-->
    <h2>Alle Bundespr&auml;sidenten und Bundesratspr&auml;sidenten mit xsl:for-each</h2>
    <ul>
      <xsl:for-each select="bundespraesident">
        <xsl:sort select="name/vorname" order="descending"/>
        <li>
          <xsl:apply-templates select="name"/>
        </li>
        <ul>
          <xsl:for-each select="bundesratspraesident">
            <xsl:sort select="name/vorname"/>
            <li>
              <xsl:apply-templates select="name"/>
            </li>
          </xsl:for-each>
        </ul>
      </xsl:for-each>
    </ul>
    <!--*****************************************************************
      ** wie gerade, aber mit xsl:apply-templates
      **************************************************************-->
    <h2>Bundespr&auml;sidenten und Bundesratspr&auml;sidenten mit xsl:apply-templates</h2>
    <ul>
      <xsl:apply-templates select="bundespraesident">
        <xsl:sort select="name/vorname" order="descending"/>
      </xsl:apply-templates>
    </ul>
  </xsl:template>
  <!--*****************************************************************
    ** Das 'Bundespraesident'-Template. Es gibt den Namen des Bundes-
    ** präsidenten aus und den des Bundesratspräsidenten.
    **************************************************************-->
  <xsl:template match="bundespraesident">
    <li>
      <xsl:apply-templates select="name"/>
    </li>
    <ul>
      <xsl:for-each select="bundesratspraesident">
        <xsl:sort select="name/vorname"/>
        <li>
          <xsl:apply-templates select="name"/>
        </li>
      </xsl:for-each>
    </ul>
  </xsl:template>
  <!--*****************************************************************
    ** Name-Template, gibt Vorname, Mittelinitial und Nachname aus
    **************************************************************-->
  <xsl:template match="name">
    <xsl:text disable-output-escaping="yes">&amp;nbsp;</xsl:text>
    <xsl:value-of select="vorname"/>
    <xsl:text disable-output-escaping="yes">&amp;nbsp;</xsl:text>
    <xsl:value-of select="mittelinitial"/>
    <xsl:text disable-output-escaping="yes">&amp;nbsp;</xsl:text>
    <xsl:value-of select="nachname"/>
    <br/>
  </xsl:template>
</xsl:stylesheet>

XSLT provides two conditional mechanisms: <xsl:if> and <xsl:choose>. They let stylesheets vary their output according to a Boolean expression that must return, as defined by XPath, either true or false.

The <xsl:if> element behaves like this Java code:

if (boolescher Ausdruck) {
// mach irgendwas
}

In XSLT the syntax is:

<xsl:if test="boolescher Ausdruck">
  <!-- Inhalt: template -->
</xsl:if>

The test attribute is required and must contain a Boolean expression. When it evaluates to true, the content is instantiated; otherwise skipped. The next example shows several uses of <xsl:if> and related XPath expressions. The highlighted lines are explained below.

Example: <xsl:if> examples

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method="html"/>
   <!--******************************************************
      ** "/"-Template
      ***************************************************-->
   <xsl:template match="/">
      <html>
         <body>
            <h1>Beispiele zu bedingter Verarbeitung</h1>
            <xsl:apply-templates select="bundespraesidenten"/>
         </body>
      </html>
   </xsl:template>
   <!--******************************************************
      ** "bundespraesidenten"-Template
      ***************************************************-->
   <xsl:template match="bundespraesidenten">
      <h3>Liste von <xsl:value-of select="count(bundespraesident)"/>Bundespräsidenten</h3>
      <ul>
         <xsl:for-each select="bundespraesident">
            <li>
               <!-- jede zweite Zeile fettgedruckt ausgeben -->
               <xsl:if test="(position( ) mod 2) = 0">
                  <xsl:attribute name="style">
                     <xsl:text>font-weight: bold;</xsl:text>
                  </xsl:attribute>
               </xsl:if>
               <xsl:apply-templates select="name"/>
               <!-- nach dem letzten Element wird noch etwas Text ausgegeben -->
               <xsl:if test="position() = last( )">
                  <xsl:text> (gegenwärtiger Bundespräsident)</xsl:text>
               </xsl:if>
            </li>
         </xsl:for-each>
      </ul>
   </xsl:template>
   <!--******************************************************
      ** "name"-Template
      ***************************************************-->
   <xsl:template match="name">
      <xsl:value-of select="nachname"/>
      <xsl:text>, </xsl:text>
      <xsl:value-of select="vorname"/>
      <xsl:if test="mittelinitial">
         <xsl:text disable-output-escaping="yes">&amp;nbsp;</xsl:text>
         <xsl:value-of select="mittelinitial"/>
      </xsl:if>
   </xsl:template>
</xsl:stylesheet>

First, template match="bundespraesidenten" prints a heading with the total number of presidents:

Liste von <xsl:value-of select="count(bundespraesidenten)"/> Bundespräsidenten

The count( ) function is an XPath node-set function, returning the element count in a node set. Here the set contains <bundespraesident> elements that are immediate children of <bundespraesidenten>. This prints the number of presidents in the XML file. The next block performs the main work, printing each president as a list item in a loop.

<xsl:for-each select="bundespraesident">
   <li>
      <!-- jede zweite Zeile fettgedruckt ausgeben -->
      <xsl:if test="(position( ) mod 2) = 0">
         <xsl:attribute name="style">
            <xsl:text>font-weight: bold;</xsl:text>
         </xsl:attribute>
      </xsl:if>
   ...

Here the <xsl:for-each> loop first selects all <bundespraesident> elements directly beneath the <bundespraesidenten> element. During iteration, function position( ) returns an integer representing the node’s position in the current list, starting at 1. Operator mod performs modulo division, returning the remainder like Java and ECMAScript’s % operator. The XPath expression (position( ) mod 2) = 0 returns true for even numbers, adding the <li> tag’s style attribute for every second president, displaying it in bold.

The template continues:

    ...
    <xsl:apply-templates select="name"/>
    <!-- nach dem letzten Element wird noch etwas Text ausgegeben -->
    <xsl:if test="position() = last( )">
      <xsl:text> (gegenwärtiger Bundespräsident)</xsl:text>
    </xsl:if>
  </li>
</xsl:for-each>

The last( ) function returns the current context size, here the number of presidents. If position equals this count, text (gegenwärtiger Bundespräsident) is appended to the result. Java programmers should note that XPath compares with a single = sign rather than Java’s ==. The resulting list HTML looks like this:

<li>Heuss, Theodor</li>
<li style="font-weight: bold;">Lübke, Heinrich</li>
<li>Heinemann, Gustav&nbsp;W.</li>
<li style="font-weight: bold;">Scheel, Walter</li>
<li>Carstens, Karl</li>
<li style="font-weight: bold;">v. Weizsäcker, Richard</li>
<li>Herzog, Roman</li>
<li style="font-weight: bold;">Rau, Johannes (gegenwärtiger Bundespräsident)</li>

The output improves on example Loops and sorting by using <xsl:if> to check for a middle name or initial:

<xsl:template match="name">
  <xsl:value-of select="nachname"/>
  <xsl:text>, </xsl:text>
  <xsl:value-of select="vorname"/>
  <xsl:if test="mittelinitial">
    <xsl:text disable-output-escaping="yes">&amp;nbsp;</xsl:text>
    <xsl:value-of select="mittelinitial"/>
  </xsl:if>
</xsl:template>

Here <xsl:if test="mittelinitial"> tests whether a node set exists rather than a Boolean expression’s value. If <mittelinitial> elements exist, the content of <xsl:if> is instantiated.

If <mittelinitial> elements exist, the first is printed. Later, example NamensFormatierung.xslt uses <xsl:for-each> to output multiple optional elements, such as titles in Dr. Dr. Gustav W. Heinemann.

Checking an attribute’s existence is similar to checking an element:

<xsl:if test="@einAttribut">
  ...diesen Code ausführen, wenn "einAttribut" vorhanden ist.
</xsl:if>

Unlike most languages, <xsl:if> has no corresponding else or otherwise. This is only a minor inconvenience, though (<xsl:choose> requires more typing), because element <xsl:choose> provides the functionality.

<xsl:choose>, <xsl:when> und <xsl:otherwise>

The XSLT equivalent of Java’s switch statement is <xsl:choose>, with equivalent functionality. Java’s switch statement works only with char, byte, short or int. <xsl:choose> expects one or more <xsl:when> elements followed by an optional <xsl:otherwise> element. The next example, <xsl:choose>, illustrates this and also uses the <xsl:variable> element covered in the next section.

 

Example: <xsl:choose>

<xsl:template match="bundespraesidenten">
   <h3>Farblich gekennzeichnet nach Parteizugehörigkeit</h3>
   <ul>
      <xsl:for-each select="bundespraesident">
         <xsl:variable name="farbe">
            <!-- hier wird die Farbe den Parteien zugeordnet -->
            <xsl:choose>
               <xsl:when test="partei = 'SPD'">
                  <xsl:text>red</xsl:text>
               </xsl:when>
               <xsl:when test="partei = 'CDU'">
                  <xsl:text>black</xsl:text>
               </xsl:when>
               <xsl:when test="partei = 'FDP'">
                  <xsl:text>yellow</xsl:text>
               </xsl:when>
               <!-- hier nie gebraucht -->
               <xsl:otherwise>
                  <xsl:text>gray</xsl:text>
               </xsl:otherwise>
            </xsl:choose>
         </xsl:variable>
         <li>
            <font color="{$farbe}">
               <xsl:apply-templates select="name"/>
               <xsl:text> - </xsl:text>
               <!-- den Namen der Partei anzeigen -->
               <xsl:value-of select="partei"/>
            </font>
         </li>
      </xsl:for-each>
   </ul>
</xsl:template>

This example lists presidents and their parties. Element <xsl:when> assigns a variable a value for each possible party. Variable farbe is then used in a font tag to give each party a different color. Element <xsl:otherwise> never runs because every president belonged to a listed party. If a future president belonged to another party, none of the <xsl:when> conditions would match and the text would be gray.

Unlike Java, XSLT requires no break statements between <xsl:when> elements. XSLT processes <xsl:when> elements in order, using only the first whose expression returns true, skipping the rest. If no <xsl:when> element matches, the optional <xsl:otherwise> element runs instead.

Since <xsl:if> has no corresponding <xsl:else>, use <xsl:choose> to emulate the behavior:

<xsl:choose>
   <xsl:when test="Bedingung">
      <!-- if-Bedingung -->
   </xsl:when>
   <xsl:otherwise>
      <!-- else-Bedingung -->
   </xsl:otherwise>
</xsl:choose>

As elsewhere in XSLT, the XML syntax requires a little more typing than Java programmers expect, but still provides if/else mechanisms.

   

 

 

 

back to top