Creating a Simple Key - Exercise

Contact Us or call 1-877-932-8228
Creating a Simple Key - Exercise

Creating a Simple Key

Duration: 10 to 15 minutes.

In this exercise, you will create and use a simple key.

  1. Open Keys/Exercises/SimpleKey.xml and review the code. You will see that it contains a list of City elements. Part of the code is shown below these instructions.
  2. Open Keys/Exercises/SimpleKey.xsl for editing.
  3. Create a key that indexes the City nodes by their State attribute.
  4. Using the key, output a City element for each City in New York State. For example:
    <City>New York</City>
  5. To test your solution, transform Keys/Exercises/SimpleKey.xml against Keys/Exercises/SimpleKey.xsl.

Code Sample:

Keys/Exercises/SimpleKey.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="SimpleKey.xsl"?>
<Cities Source="http://www.city-data.com/top1.html">
	<City State="NY" Population="8084316">New York</City>
	<City State="CA" Population="3798981">Los Angeles</City>
	<City State="IL" Population="2886251">Chicago</City>
	<City State="TX" Population="2009834">Houston</City>
	<City State="PA" Population="1492231">Philadelphia</City>
	<City State="AZ" Population="1371960">Phoenix</City>
	<City State="CA" Population="1259532">San Diego</City>
	<City State="TX" Population="1211467">Dallas</City>
	<City State="TX" Population="1194222">San Antonio</City>
---- C O D E   O M I T T E D ----

</Cities>

Code Sample:

Keys/Exercises/SimpleKey.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"/>
	<!--Create a key that indexes the City nodes by their State attribute.-->
	<xsl:template match="/">
		<Cities>
			<!--Output a City element for each City in New York State.-->
		</Cities>
	</xsl:template>
</xsl:stylesheet>

Solution:

Keys/Solutions/SimpleKey.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:key name="keyCity" match="City" use="@State"/>
	<xsl:param name="State" select="'NY'"/>
	<xsl:template match="/">
		<Cities>
			<xsl:for-each select="key('keyCity',$State)">
				<City><xsl:value-of select="."/></City>
			</xsl:for-each>
		</Cities>
	</xsl:template>
</xsl:stylesheet>
Next