The xsl:apply-templates ElementThe template I used in the previous section applied only to one node, the root node, and it performed a trivial action, replacing the entire XML document with an HTML document. However, you can also apply templates to the children of a node that you've matched, and you do that with the <xsl:apply-templates> element. For example, say that I want to convert ch13_01.xml to HTML. The document node in that document is <PLANETS> , so I can match that element with a template, setting the match attribute to the name of the element I want to match. Then I can replace the <PLANETS> element with an <HTML> element, like this: <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="PLANETS"> <HTML> . . . </HTML> </xsl:template> . . . </xsl:stylesheet> But what about the children of the <PLANETS> element? To make sure they are transformed correctly, you use the <xsl:apply-templates> element this way: <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="PLANETS"> <HTML> <xsl:apply-templates/> </HTML> </xsl:template> . . . </xsl:stylesheet> Now you can provide templates for the child nodes. In this case, I'll just replace each of the three <PLANET> elements with some text that I place directly into the template for the <PLANET> element: Listing ch13_06.xsl<?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="PLANETS"> <HTML> <xsl:apply-templates/> </HTML> </xsl:template> <xsl:template match="PLANET"> <P> Planet data will go here.... </P> </xsl:template> </xsl:stylesheet> And that's it. Now the <PLANETS> element is replaced by an <HTML> element, and the <PLANET> elements are also replaced: <HTML> <P> Planet data will go here.... </P> <P> Planet data will go here.... </P> <P> Planet data will go here.... </P> </HTML> You can see that this transformation works, but it's still less than useful; all we've done is replace the <PLANET> elements with some text. What if we want to access some of the data in the <PLANET> element? For example, say that we want to place the text from the <NAME> element in each <PLANET> element in the output document: <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 gain access to this kind of data, you can use the select attribute of the <xsl:value-of> element. |