6

I am trying to convert an XML to JSON using XSLT. Following are my XML and XSLT code.

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>

Output of XSLT:

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

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

0

1 Answer 1

11

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

So basically you have to wrap that comma in a xsl:if statement like this: <xsl:if test="./following-sibling::cd">,</xsl:if>

So your stylesheet will look something like that:

<?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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.