XML - Managing Data Exchange/XPath/Answers

From Wikibooks, open books for an open world
Jump to navigation Jump to search

XPath Chapter => XPath

XPath Exercises => Exercises


XML

Exercises[edit | edit source]

In this exercise, you will modify the xsl-tree.xsl file we saw in chapter 8 XPath to...


  1. Print the name attribute of every bigBranch element with thickness set as ‘thick’.
  2. Print the name of the parent of each bigBranch.
  3. Print the color of all leaves with a color attribute.


Answers[edit | edit source]

1. Print the name attribute of every bigBranch element with thickness set as ‘thick’[edit | edit source]

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[edit | edit source]

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[edit | edit source]

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