tags:

views:

43

answers:

2

Hi, I'm trying to write XSLT to transform a specific web page to JSON. The following code demonstrates how Ruby would do this conversion, but the XSLT doesn't generate valid JSON (there's one too many commas inside the array) - anyone know how to write XSLT to generate valid JSON?

require 'rubygems'
require 'nokogiri'
require 'open-uri'

doc = Nokogiri::HTML(open('http://bbc.co.uk/radio1/playlist'))
xslt = Nokogiri::XSLT(DATA.read)

puts out = xslt.transform(doc)

# Now follows the XSLT
__END__
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml"&gt;
    <xsl:output method="text" encoding="UTF-8" media-type="text/plain"/>

    <xsl:template match="/">
        [
        <xsl:for-each select="//*[@id='playlist_a']//div[@class='artists_and_songs']//ul[@class='clearme']">
            {'artist':'<xsl:value-of select="li[@class='artist']" />','track':'<xsl:value-of select="li[@class='song']" />'},
        </xsl:for-each>
        ]
    </xsl:template>
</xsl:stylesheet>
+4  A: 

Omit the comma from the line inside the for-each and add:

<xsl:if test="position() != last()">,</xsl:if>

This will add a comma to each item except the last one.

Greg Hewgill
IMHO, position() is XSLT's only flash-of-genius feature.
Max A.
Excellent. Cheers!
JP
A: 

Splitting up your XSLT into separate templates can help increasing readability.

<xsl:stylesheet
  version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
  xmlns="http://www.w3.org/1999/xhtml"
>
  <xsl:output method="text" encoding="UTF-8" media-type="text/plain"/>

  <xsl:template match="/">
    <xsl:text>[</xsl:text>
    <xsl:apply-templates select="//div[@id='playlist_a']//ul[@class='clearme']" />
    <xsl:text>]</xsl:text>
  </xsl:template>

  <xsl:template match="ul">
    <xsl:text>{'artist':'</xsl:text><xsl:value-of select="li[@class='artist']" />
    <xsl:text>','track':'</xsl:text><xsl:value-of select="li[@class='song']" />
    <xsl:text>'}</xsl:text>
    <xsl:if test="position() &lt; last()">,</xsl:if>
  </xsl:template>
</xsl:stylesheet>

Also, the values of artist and song can break your JSON if they contain single quotes, replacing single quotes could be necessary.

Tomalak