BibleGateway.com Verse Of The Day

Wednesday, February 01, 2006

iTunes Library.xml, Meet XSLT

If you've looked at the iTunes Library.xml file, you were probably shocked at how cryptic XML can be. You have a list of songs and playlists, with attributes such as song name, album, band, etc. Seems simple, but that XML is UGLY.I found this XSL sniipet on the web somewhere and started to play with it. I'm not an XSL guru by any means, but I've hacked together a couple XSL transformations to make some sense of the Library. In this case, it is a two step process (I'm sure it could be boiled down to 1, but I'm not XSL guru, remember?). This creates a simple HTML table with song, album, band, genre, etc.

Step 1: Flatten out the relations a little to make it look more like you expected in the first place:



<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
<tracks>
<xsl:apply-templates select="plist/dict/dict/dict"/>
</tracks>
</xsl:template>

<xsl:template match="dict">
<track>
<xsl:apply-templates select="key"/>
</track>
</xsl:template>

<xsl:template match="key">
<xsl:element name="{translate(text(), ' ', '_')}">
<xsl:value-of select="following-sibling::node()[1]"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>



STEP 2: Render the output the way you want it, simple example shown below:



<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body bgcolor="navy">
<table border="1" align="center" bgcolor="silver" width="90%">
<tr>
<th bgcolor="#8b9ffe">Artist</th>
<th bgcolor="#8b9ffe">Album</th>
<th bgcolor="#8b9ffe">Year</th>
<th bgcolor="#8b9ffe">Track</th>
<th bgcolor="#8b9ffe">Song</th>
<th bgcolor="#8b9ffe">Genre</th>
</tr>
<xsl:for-each select="/tracks/track">
<xsl:sort data-type="text" order="ascending" select="Artist"/>
<xsl:sort data-type="text" order="ascending" select="Year"/>
<xsl:sort data-type="text" order="ascending" select="Album"/>
<xsl:sort data-type="number" order="ascending" select="Disc_Number"/>
<xsl:sort data-type="number" order="ascending" select="Track_Number"/>
<tr>
<td><xsl:value-of select="Artist"/></td>
<td> <xsl:value-of select="Album"/></td>
<td> <xsl:value-of select="Year"/></td>
<td>
<xsl:value-of select="Disc_Number"/>
<xsl:text> </xsl:text>
<xsl:value-of select="Track_Number"/>
</td>
<td> <xsl:value-of select="Name"/> </td>
<td> <xsl:value-of select="Genre"/> </td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

No comments: