Using xsl:apply-templates - Exercise

Contact Us or call 1-877-932-8228
Using xsl:apply-templates - Exercise

Using xsl:apply-templates

Duration: 15 to 25 minutes.

In this exercise, you will practice using xsl:apply-templates.

  1. Open TemplatesParametersVariables/Exercises/BeatlesTemplates.xsl.
  2. There is already an xsl:template that matches the root node. Within this template, add two xsl:apply-templates, one that matches real Beatles and one that matches fake Beatles.
  3. After the initial xsl:template, create new templates for the beatle elements and for firstname and lastname elements.
    • Note that there should separate templates for real Beatles and for fake Beatles.
    • The real beatles should be enclosed in <Real></Real> tags.
    • The fake beatles should be enclosed in <Fake></Fake> tags.
    • The first names should be enclosed in <FirstName></FirstName> tags.
    • The last names should be enclosed in <LastName></LastName> tags.
  4. To test your solution, transform TemplatesParametersVariables/Exercises/BeatlesTemplates.xml against TemplatesParametersVariables/Exercises/BeatlesTemplates.xsl. The output is below.

Code Sample:

TemplatesParametersVariables/Exercises/TemplatesOutput.xml
<?xml version="1.0" encoding="UTF-8"?>
<Beatles>
	<RealBeatles>
		<Real>
			<FirstName>Paul</FirstName>
			<LastName>McCartney</LastName>
		</Real>
		<Real>
			<FirstName>John</FirstName>
			<LastName>Lennon</LastName>
		</Real>
		<Real>
			<FirstName>George</FirstName>
			<LastName>Harrison</LastName>
		</Real>
		<Real>
			<FirstName>Ringo</FirstName>
			<LastName>Starr</LastName>
		</Real>
	</RealBeatles>
	<FakeBeatles>
		<Fake>
			<FirstName>Nat</FirstName>
			<LastName>Dunn</LastName>
		</Fake>
	</FakeBeatles>
</Beatles>

Solution:

TemplatesParametersVariables/Solutions/BeatlesTemplates.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" 
				xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
	<xsl:output method="xml" indent="yes"/>
	<xsl:template match="/">
		<Beatles>
			<RealBeatles>
				<xsl:apply-templates select="beatles/beatle[not(@real='no')]"/>
			</RealBeatles>
			<FakeBeatles>
				<xsl:apply-templates select="beatles/beatle[@real='no']"/>
			</FakeBeatles>
		</Beatles>
	</xsl:template>
	<xsl:template match="beatle[not(@real='no')]">
		<Real><xsl:apply-templates/></Real>
	</xsl:template>
	<xsl:template match="beatle">
		<Fake><xsl:apply-templates/></Fake>
	</xsl:template>
	<xsl:template match="firstname">
		<FirstName><xsl:apply-templates/></FirstName>
	</xsl:template>
	<xsl:template match="lastname">
		<LastName><xsl:apply-templates/></LastName>
	</xsl:template>
</xsl:stylesheet>
Next