Processing Child Nodes

Processing Child Nodes

You use the <xsl:apply-templates> element to tell the XSLT processor it should process any matching templates for child nodes of the context node. The <xsl:apply-templates> element enables you to indicate exactly when the processing of child nodes should be finished, and thats crucial if you want to insert their data into the HTML table at the correct point.

One important point often causes confusion: The <xsl:apply-templates> element applies templates to only the child nodes of the context or selected node or node set, by default. That seems innocuous enough, but what many people forget is that attributes are not considered child nodes of elements, and for that matter, neither are namespace declarations. That means you have to take an extra step or two if you want to process attributes as well as elements, as youll see in this chapter.

In the following example, you place the <xsl:apply-templates> element at the point where you want to insert the data from the <PLANET> elements into the HTML table. Ill also add a new template to handle the <PLANET> elements:

 <?xml version="1.0"?>  <xsl:stylesheet version="1.0"  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">      <xsl:template match="/PLANETS">          <HTML>              <HEAD>                  <TITLE>                      The Planets Table                  </TITLE>              </HEAD>              <BODY>                  <H1>                      The Planets Table                  </H1>                  <TABLE BORDER="2">                      <TR>                          <TD>Name</TD>                          <TD>Mass</TD>                          <TD>Radius</TD>                          <TD>Day</TD>                      </TR>                      <xsl:apply-templates/>                  </TABLE>              </BODY>          </HTML>      </xsl:template>      <xsl:template match="PLANET">          .          .          .     </xsl:template>  </xsl:stylesheet> 

In the new template that handles <PLANET> elements, I have to recover the data in each <PLANET> element, which means I have to recover the values in the child elements of the <PLANET> element, such as <MASS> , <DAY> , and so on:

 <?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>          .          .          . 

You can do that with the <xsl:value-of> element.



Inside XSLT
Inside Xslt
ISBN: B0031W8M4K
EAN: N/A
Year: 2005
Pages: 196

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net