WebReference.com - Excerpt from Inside XSLT, Chapter 2, Part 3 (4/5) | WebReference

WebReference.com - Excerpt from Inside XSLT, Chapter 2, Part 3 (4/5)

To page 1To page 2To page 3current pageTo page 5
[previous] [next]

Inside XSLT

The <xsl:apply-templates> Element

In the basic template we've already written, the root node has been matched with the expression "/" and replaced with a literal result element. However, when you match the root node, you usually have the whole rest of the document to work on, and we'll do that with the <xsl:apply-templates> element.

The following list includes the attributes of the <xsl:apply-templates> element:

The <xsl:apply-templates> element can contain zero or more <xsl:sort> elements, or zero or more <xsl:with-param> elements.

In the following example, the template matches the root node, and replaces it with the <HTML> literal result element:

<?xml version="1.0">
<xsl:stylesheet version="1.0" 
xmlns:xsl="https://www.w3.org/1999/XSL/Transform">
   <xsl:template match="/">
       <HTML>
       </HTML>
   </xsl:template>
        .
        .
        .

On the other hand, we've only matched the root node, and the planets.xml data tree has a number of nodes under the root node:

<?xml version="1.0"?>
<?xml-stylesheet type="text/xml" href="planets.xsl"?>
<PLANETS>
  <PLANET>
     <NAME>Mercury</NAME>
     <MASS UNITS="(Earth = 1)">.0553</MASS>
     <DAY UNITS="days">58.65</DAY>
     <RADIUS UNITS="miles">1516</RADIUS>
     <DENSITY UNITS="(Earth = 1)">.983</DENSITY>
     <DISTANCE UNITS="million miles">43.4</DISTANCE><!--At perihelion-->
  </PLANET>
        .
        .
        .

To process more than just the root node, you can use <xsl:apply-templates> by adding that element like this:

<?xml version="1.0">
<xsl:stylesheet version="1.0" 
xmlns:xsl="https://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <HTML>
      <xsl:apply-templates/>
    </HTML>
  </xsl:template>
        .
        .
        .

This element makes the XSLT processor look at any child nodes of the root node and try to find any template that matches those nodes. For example, you might want to replace all <PLANET> elements with <P>Planet</P>. The <PLANET> elements are children of the <PLANETS> element, so I add a new template for <PLANETS> first, just telling the XSLT processor to keep searching for child nodes:

<?xml version="1.0">
<xsl:stylesheet version="1.0" 
xmlns:xsl="https://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <HTML>
      <xsl:apply-templates/>
    </HTML>
  </xsl:template>
  <xsl:template match="PLANETS">
    <xsl:apply-templates/>
  </xsl:template>
        .
        .
        .

To page 1To page 2To page 3current pageTo page 5
[previous] [next]

Created: September 26, 2001
Revised: September 26, 2001


URL: https://webreference.com/authoring/languages/xml/insidexslt/chap2/3/4.html