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="">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
<xsl:apply-templates select="plist/dict/dict/dict"/>

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

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

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="">
<xsl:template match="/">
<body bgcolor="navy">
<table border="1" align="center" bgcolor="silver" width="90%">
<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>
<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"/>
<td><xsl:value-of select="Artist"/></td>
<td> <xsl:value-of select="Album"/></td>
<td> <xsl:value-of select="Year"/></td>
<xsl:value-of select="Disc_Number"/>
<xsl:text> </xsl:text>
<xsl:value-of select="Track_Number"/>
<td> <xsl:value-of select="Name"/> </td>
<td> <xsl:value-of select="Genre"/> </td>

No comments: