如何使用XSLT1.0模板从作者处获取书籍
我对XSLT1.0有疑问。任务是用HTML写出给定作者仅使用XSL模板编写的所有书籍如何使用XSLT1.0模板从作者处获取书籍,xslt,Xslt,我对XSLT1.0有疑问。任务是用HTML写出给定作者仅使用XSL模板编写的所有书籍 <?xml version="1.0" encoding="UTF-8"?> <books> <book author="herbert"> <name>Dune</name> </book> <book author="herbert">
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book author="herbert">
<name>Dune</name>
</book>
<book author="herbert">
<name>Chapterhouse: Dune</name>
</book>
<book author="pullman">
<name>Lyras's Oxford</name>
</book>
<book author="pratchett">
<name>I Shall Wear Midnight</name>
</book>
<book author="pratchett">
<name>Going Postal</name>
</book>
<author id="pratchett"><name>Terry Pratchett</name></author>
<author id="herbert"><name>Frank Herbert</name></author>
<author id="pullman"><name>Philip Pullman</name></author>
</books>
沙丘
教堂:沙丘
里拉斯牛津酒店
我将穿午夜礼服
邮寄
泰瑞·普莱契
弗兰克·赫伯特
菲利普·普尔曼
到目前为止,我有这个解决方案
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html"/>
<xsl:template match="/">
<html>
<head/>
<body>
<table border="1">
<xsl:apply-templates select="//author"/>
</table>
</body>
</html>
</xsl:template>
<xsl:template match="author">
<tr>
<td>
<xsl:value-of select="name/text()"/>
</td>
<td>
<xsl:value-of select="@id"/>
</td>
<td>
<xsl:apply-templates select="/books/book[@id=@author]"/>
--previous XPath does not work properly, it should choose only those books that are written by the given author (that this template matches)
</td>
</tr>
</xsl:template>
<xsl:template match="book">
<xsl:value-of select="name/text()"/>
</xsl:template>
</xsl:stylesheet>
--以前的XPath无法正常工作,它应该只选择由给定作者编写的书籍(此模板匹配)
不过,有一个问题,在评论中解释道
谢谢Martin和Marzipan-现在可以用了。还有一件事。如果我想让每一位作者的书名用逗号隔开怎么办?我提出了这个解决方案,但有没有更优雅的方法来实现这一点
,
我才意识到我的问题已经被Marzipan回答了。然后问题就解决了。您想要
或者更好的是一个键(作为xsl:stylesheet元素的子元素):
然后
问题是这一行:
<xsl:apply-templates select="/books/book[@id=@author]"/>
请理解,当您输入谓词时,上下文将更改为前面的XPath选择器匹配的节点。上下文不再是与其所在模板匹配的节点
为了解决这个问题,将作者的ID提交给一个变量,然后在谓词中使用它
<xsl:variable name='author_id' select='@id' />
...
[@author=$author_id]
...
[@author=$author\u id]
[编辑-或者,正如马丁在回答中指出的,使用current()
强制上下文]
您可以在此处运行它:
<xsl:apply-templates select="/books/book[@id=@author]"/>
<xsl:variable name='author_id' select='@id' />
...
[@author=$author_id]