Writing JSON with XSLT Writing JSON with XSLT json json

Writing JSON with XSLT


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.


Splitting up your XSLT into separate templates can increase 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() < 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.


Why not use the Sitecore Item Web API instead? It is available on SDN and is installed as a simple plugin. When it is installed you can use REST to get items back as JSON. It is possible to search for items and you can set security for the individual fields available through JSON. Further on you can actually create, delete and update Sitecore items using REST and JSON.