< XML - Managing Data Exchange < XPath 
 
 
      XPath Chapter => XPath
XPath Exercises => Exercises
Exercises
In this exercise, you will modify the xsl-tree.xsl file we saw in chapter 8 XPath to...
- Print the name attribute of every bigBranch element with thickness set as ‘thick’.
- Print the name of the parent of each bigBranch.
- Print the color of all leaves with a color attribute.
Answers
1. Print the name attribute of every bigBranch element with thickness set as ‘thick’
xsl-tree1.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="html"/> <xsl:template match="/child::trunk"> <html> <head> <title>XPath Tree Tests</title> </head> <body> <xsl:for-each select="child::bigBranch[attribute::thickness='thick']"> <xsl:call-template name="print_out"/> </xsl:for-each> </body> </html> </xsl:template> <xsl:template name="print_out"> <xsl:value-of select="attribute::name"/> <br/> </xsl:template> </xsl:stylesheet> | 
Output
| bb1 | 
2. Print the name of the parent of each bigBranch
xsl-tree2.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="html"/> <xsl:template match="/child::trunk"> <html> <head> <title>XPath Tree Tests</title> </head> <body> <xsl:for-each select="child::bigBranch"> <xsl:call-template name="print_out"/> </xsl:for-each> </body> </html> </xsl:template> <xsl:template name="print_out"> <xsl:value-of select="parent::node()/attribute::name"/> <br/> </xsl:template> </xsl:stylesheet> | 
Output
| the_trunk the_trunk the_trunk | 
3. Print the color of all leaves with a color attribute
xsl-tree3.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="html"/>
	<xsl:template match="/child::trunk">
		<html>
			<head>
				<title>XPath Tree Tests</title>
			</head>
			<body>
				<xsl:for-each select="descendant::leaf[string(attribute::color) != '']">
					<xsl:call-template name="print_out"/>
				</xsl:for-each>
			</body>
		</html>
	</xsl:template>
	<xsl:template name="print_out">
		<xsl:value-of select="attribute::name"/>, <xsl:value-of select="attribute::color"/>
		<br/>
	</xsl:template>
</xsl:stylesheet>
 | 
Output
| leaf1, brown leaf5, purple leaf9, black leaf14, red leaf17, red | 
XPath Chapter => XPath
XPath Exercises => Exercises
    This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.