Problems Converting XML to JSON Using XSLT

I am trying to convert XML to JSON using XSLT. Below are my XML and XSLT codes.

XML file:

<?xml version="1.0" encoding="ISO-8859-1"?> <catalog> <cd> <title>Empire Burlesque</title> <artist>Bob Dylan</artist> <country>USA</country> <price>10.90</price> <year>1985</year> </cd> <cd> <title>Subrayana kathe</title> <artist>Subba</artist> <country>India</country> <price>30</price> <year>1986</year> </cd> </catalog> 

XSLT File:

 <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> { "catalog":[ <xsl:for-each select="catalog/cd"> {"title":" <xsl:value-of select="title" /> ", "artist":" <xsl:value-of select="artist" /> "}, </xsl:for-each> ] } </xsl:template> </xsl:stylesheet> 

XSLT Output:

 { "catalog":[ { "title":"Empire Burlesque", "artist":"Bob Dylan" }, { "title":"Subrayana kathe", "artist":"Subba" },(Problematic comma) ] } 

The problem is that at the end of the last object in the array there is an extra comma (','). Is there any way to avoid this in XSLT?

+6
source share
1 answer

Only write a comma if there is another cd element in your xml.

So basically you should wrap this comma in the xsl:if as follows: <xsl:if test="./following-sibling::cd">,</xsl:if>

So your stylesheet will look something like this:

 <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> { "catalog":[ <xsl:for-each select="catalog/cd"> {"title":" <xsl:value-of select="title" /> ", "artist":" <xsl:value-of select="artist" /> "}<xsl:if test="./following-sibling::cd">,</xsl:if> </xsl:for-each> ] } </xsl:template> </xsl:stylesheet> 
+11
source

All Articles