Connecting Tech Pros Worldwide Forums | Help | Site Map

Smartest way to sort data with XSLT and display it

Omega375
Guest
 
Posts: n/a
#1: Aug 2 '05
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!


Joris Gillis
Guest
 
Posts: n/a
#2: Aug 2 '05

re: Smartest way to sort data with XSLT and display it


Hi,

Tempore 11:18:00, die Tuesday 02 August 2005 AD, hinc in foro {comp.text.xml} scripsit Omega375 <safaridonna@gmail.com>:
[color=blue]
> 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']".[/color]
Yes, but it's more CPU-friendly to use keys.
[color=blue]
> This is where my problem is;
> I don't knwo which authors that do exist in the xml-file.[/color]

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:output 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,
--
Joris Gillis (http://users.telenet.be/root-jg/me.html)
«Η αλήθεια και το λάδι πάντα βγαίνουν από πάνω»
Closed Thread