另一个问题是,在你知道你写下的元素不会有其他子元素时,只需说apply-templates是否正常。在我的情况下,在匹配文档根的模板中我说apply-templates。然后它找到了ebooks,这是它的唯一子元素,但我可能会有一个“books”元素,区分“普通”图书和电子图书,那么它将只列出书籍的字符数据。如果我只想在我的最终文档中获取ebooks,那么我就需要编写apply-templates select="ebooks"。所以这是一种情况,取决于你对文档了解多少?
谢谢,这里是我的代码(仅供练习):
XML:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="ebooks.xsl"?>
<ebooks>
<ebook>
<title>Advanced Rails Recipes: 84 New Ways to Build Stunning Rails Apps</title>
<authors>
<author><name>Mike Clark</name></author>
</authors>
<pages>464</pages>
<isbn>978-0-9787-3922-5</isbn>
<programming_language>Ruby</programming_language>
<date>
<year>2008</year>
<month>5</month>
<day>1</day>
</date>
<publisher>The Pragmatic Programmers</publisher>
</ebook>
...
XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<html>
<head>
<title>Library</title>
</head>
<body>
<xsl:apply-templates />
</body>
</html>
</xsl:template>
<xsl:template match="ebooks">
<h1>Ebooks</h1>
<xsl:apply-templates>
<xsl:sort select="title"/>
</xsl:apply-templates>
</xsl:template>
<xsl:template match="ebook">
<h3><xsl:value-of select="title"/></h3>
<xsl:apply-templates select="date" />
<xsl:for-each select="authors/author/name">
<b><xsl:value-of select="."/>,</b>
</xsl:for-each>
</xsl:template>
<xsl:template match="date">
<table border="1">
<tr>
<th>Day</th>
<th>Month</th>
<th>Year</th>
</tr>
<tr>
<td><xsl:value-of select="day"/></td>
<td><xsl:value-of select="month"/></td>
<td><xsl:value-of select="year"/></td>
</tr>
</table>
</xsl:template>
</xsl:stylesheet>