I have question about XSLT1.0. The task is to write out in HTML all books written by given authors only by using XSL templates.
<?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>
So far I have this solution.
<?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>
There is a problem though, explained in the comment.
Thank you Martin and Marzipan – it works now. There is one more thing. What if I wanted to have the book titles for each authors separated by commas? I propose this solution, but is there more elegant way to achieve this?
…
<xsl:apply-templates select="/books/book[current()/@id=@author][not(position()=last())]" mode="notLast"/>
<xsl:apply-templates select="/books/book[current()/@id=@author][last()]"/>
</td>
</tr>
</xsl:template>
<xsl:template match="book">
<xsl:value-of select="name/text()"/>
</xsl:template>
<xsl:template match="book" mode="notLast">
<xsl:value-of select="name/text()"/>
<xsl:text> , </xsl:text>
</xsl:template>
</xsl:stylesheet>
I just realized my question has been already answered by Marzipan. Quesion is solved then.
You want
<xsl:apply-templates select="/books/book[current()/@id=@author]"/>or better yet a key (as a child of the xsl:stylesheet element):and then
<xsl:apply-templates select="key('book-by-author', @id)"/>.