Smartest way to sort data with XSLT and display it

O

Omega375

Hello.

I'll first start off by showing the structure of my xml-file.

<root>
<node path="X">
More nodes containing data
</node>
</root>


Let's see this like books;

<books>
<book author="X">
More nodes containing data
</book>
</books>

What I now want to do (with XSLT) is to display all the books by the
author, eg;

JK Rowling
* Harry Potter 1
* Harry Potter 2

Tolkien
* LOTHR 1
* LOTHR 2

....


This can easly be done by using xpath "books/book[@author='JK
Rowling']".
This is where my problem is;
I don't knwo which authors that do exist in the xml-file. So somehow I
have to find all the names of the authors and then pass the names, one
by one, to the xpath.

I don't think adding

<authors>
<author>Name</author>
...
</authors>

to the xml-file is an option.

I sure hope someone knows how to solve this problem.

Thank you in advance!
 
J

Joris Gillis

Hi,

Tempore 11:18:00 said:
What I now want to do (with XSLT) is to display all the books by the
author, eg;

This can easly be done by using xpath "books/book[@author='JK
Rowling']".
Yes, but it's more CPU-friendly to use keys.
This is where my problem is;
I don't knwo which authors that do exist in the xml-file.

In some way, you need to obtain a list containing all possible author names without duplicates. This can be achieved with grouping. That's a built in job in XSLT 2.0, but in XSLT 1.0, you need to build a grouping algorithm yourself.
Consider this example (using the popular Muenchian grouping technique):

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:eek:utput method="text"/>

<xsl:key name="bookByAuthor" match="book" use="@author"/>
<xsl:variable name="allAuthors" select="//book[generate-id()=generate-id(key('bookByAuthor',@author)[1])]/@author"/>

<xsl:template match="books">
<xsl:for-each select="$allAuthors">
<xsl:value-of select="."/>
<xsl:text>
</xsl:text>
<xsl:apply-templates select="key('bookByAuthor',.)"/>
</xsl:for-each>
</xsl:template>

<xsl:template match="book">
<xsl:text> * </xsl:text>
<xsl:apply-templates/>
<xsl:text>
</xsl:text>
</xsl:template>

<xsl:template match="text()">
<xsl:value-of select="normalize-space(.)"/>
</xsl:template>

</xsl:stylesheet>


regards,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,240
Members
46,830
Latest member
HeleneMull

Latest Threads

Top