我正在尝试学习XSLT 2.0。在下面的示例中,我试图列出每种语言可用的语言和书籍。您能帮我理解上下文的工作原理吗?
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="Library.xsl"?>
<Library>
<Books>
<Book>
<Language code="English">English</Language>
<code>1</code>
<Title>History</Title>
</Book>
<Book>
<Language code="Spanish">Spanish</Language>
<code>2</code>
<Title>Math</Title>
</Book>
</Books>
<Languages>
<Language code="English">English</Language>
<Language code="Spanish">Spanish</Language>
</Languages>
</Library>
//样式表
<?xml version="1.0"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<table>
<xsl:for-each select="/Library/Languages/Language">
<tr>
<td style="border:1px solid red;">
<xsl:value-of select="@code" /><br /><br />
<xsl:variable name="key" select="@code" />
</td>
</tr>
<xsl:for-each select="/Library/Books/Book">
<xsl:if test="Language[@code=string($key)]">
<tr>
<td style="border:1px solid red;">
<xsl:value-of select="@code" />
</td>
</tr>
</xsl:if>
</xsl:for-each>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
//所需的输出:
Language: English
Title: English Book
Language: Spanish
Title: Spanish Book
答案 0 :(得分:0)
要获得所需的输出,可以将XSLT-1.0文件更改为以下文件(似乎不需要XSLT-2.0)。一个关键方面是将<xsl:variable name="key" select="@code" />
从td
元素中移出两层,以便可以在xsl:for-each
中对其进行访问。
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<table>
<xsl:for-each select="/Library/Languages/Language">
<xsl:variable name="key" select="@code" />
<tr>
<td style="border:1px solid red;">
<xsl:value-of select="concat('Language: ', @code)" /><br /><br />
</td>
</tr>
<xsl:for-each select="/Library/Books/Book[Language[@code=$key]]">
<tr>
<td style="border:1px solid red;">
<xsl:value-of select="concat('Title: ', $key,' Book')" />
</td>
</tr>
</xsl:for-each>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
输出为:
<html>
<body>
<table>
<tr>
<td style="border:1px solid red;">Language: English</td>
</tr>
<tr>
<td style="border:1px solid red;">Title: English Book</td>
</tr>
<tr>
<td style="border:1px solid red;">Language: Spanish</td>
</tr>
<tr>
<td style="border:1px solid red;">Title: Spanish Book</td>
</tr>
</table>
</body>
</html>