11. <xsl:apply-templates> and <xsl:value-of>

In the previous section, it was explained that <xsl:apply-templates> can be used as an alternative for <xsl:for-each>. The element <xsl:apply-templates> can also be used as an alternative for <xsl:value-of>.

In the fragment below, all <xsl:value-of> elements have been replaced with <xsl:apply-templates>.

<xsl:template match="letter">

      <b>From <xsl:apply-templates select="author"/>
      to
      <xsl:apply-templates select="recipient"/></b>
      <br/>

      <xsl:apply-templates select="place"/> <br/>


      <xsl:apply-templates select="year"/><br/>


      <xsl:apply-templates select="callnumber"/><br/>


</xsl:template>
    

The result of the transformation will be exactly the same, despite the fact that no templates have been included for the elements that are referred to in the <xsl:apply-templates> elements. These elements are transformed nevertheless. The reason for this is that when a template is missing for a certain element, the XSLT processor will use a default template. This default template does not contain any specifications for a specific presentation. The only thing that happens is that the contents of this element are selected. The <xsl:apply-templates> element will inially instruct the XSLT processor to search for matching templates for the elements it finds. In the absence of such a template, the default template will be used. Using <xsl:apply-templates> instead of <xsl:value-of> thus has the exact same effect in this particular stylesheet.

Note, additionally, that templates will be invoked ONLY if there are matching elements in the XML source documents, so it is no longer necessary to work with <xsl:if>.

The advantages of using <xsl:apply-templates> can be illustrated by adding another template specifically for the <note> element. As can be seen in the tree dragram in section 2, this is an element that can be found at a lower branch of the XML tree, underneath <annotations>.

<xsl:template match="note">

  <i>
      <xsl:text>- </xsl:text>
      <xsl:value-of select="."/>
  </i>
  <br/>

</xsl:template>

    

The transformed file will then look as follows:

The result does not simply display the text of the element <note>. The notes are displayed using the instructions in this specific template.