跳轉到內容

XML - 資料交換管理/XPath/答案

來自華夏公益教科書,開放的書籍,開放的世界

XPath 章節 => XPath

XPath 練習 => 練習


XML

在本練習中,您將修改我們在第 8 章 XPath 中看到的 xsl-tree.xsl 檔案來...


  1. 列印所有 thickness 屬性設定為 ‘thick’ 的 bigBranch 元素的 name 屬性。
  2. 列印每個 bigBranch 的父節點的名稱。
  3. 列印所有具有 color 屬性的葉子節點的顏色。


1. 列印所有 thickness 屬性設定為 ‘thick’ 的 bigBranch 元素的 name 屬性

[編輯 | 編輯原始碼]

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>

輸出

bb1


2. 列印每個 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>

輸出

the_trunk
the_trunk
the_trunk

3. 列印所有具有 color 屬性的葉子節點的顏色

[編輯 | 編輯原始碼]

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>

輸出

leaf1, brown
leaf5, purple
leaf9, black
leaf14, red
leaf17, red

XPath 章節 => XPath

XPath 練習 => 練習

華夏公益教科書