Looping with xsl:for-each - Exercise

Contact Us or call 1-877-932-8228
Looping with xsl:for-each - Exercise

Looping with xsl:for-each

Duration: 10 to 15 minutes.

In this exercise, you will use xsl:for-each to transform FlowControl/Exercises/BusinessLetter.xml to produce the following output.

Code Sample:

FlowControl/Exercises/ForEachOutput.xml
<?xml version="1.0" encoding="UTF-8"?>
<Names>
	<Name>
		<Title>Mr.</Title>
		<FName>Joshua</FName>
		<LName>Lockwood</LName>
	</Name>
	<Name>
		<Title></Title>
		<FName>Bill </FName>
		<LName>Smith</LName>
	</Name>
	<Name>
		<Title></Title>
		<FName>Bill </FName>
		<LName>Smith</LName>
	</Name>
</Names>
  1. Open FlowControl/Exercises/ForEach.xsl for editing.
  2. Beneath the comment, add an xsl:for-each tag that will output a Name element that contains three child elements: Title, FName, and LName.
  3. The values of the child elements should be retrieved from the source document (FlowControl/Exercises/BusinessLetter.xml).
  4. To test your solution, transform FlowControl/Exercises/BusinessLetter.xml against FlowControl/Exercises/ForEach.xsl.

Solution:

FlowControl/Solutions/ForEach.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="/">
		<Names>
		<xsl:for-each select="//Name">
				<Name>
					<Title><xsl:value-of select="@Title"/></Title>
					<FName><xsl:value-of select="FirstName"/></FName>
					<LName><xsl:value-of select="LastName"/></LName>
				</Name>
		</xsl:for-each>
		</Names>
	</xsl:template>
</xsl:stylesheet>
Next