Search code examples
jsonxmlxsltxslt-1.0xml-to-json

What is the XSLT to convert the below XML into JSON?


<?xml version="1.0" encoding="UTF-8"?>
<!--Generated by Oracle BI Publisher -Dataengine, datamodel:_Custom_OAL_ATG_OM_Dashboard_DM_xdm -->
<DATA>
<SUCCESS>
<COUNT___>5686</COUNT___>
</SUCCESS>
<REJECT>
<COUNT___>641</COUNT___>
</REJECT>
<FAILURE>
<COUNT___>8536</COUNT___>
</FAILURE>
<ERROR>
<COUNT___>1447</COUNT___>
</ERROR>
<TERMINATED>
<COUNT___>1341</COUNT___>
</TERMINATED>
</DATA>

Above is the XML I have. I want to convert the above XML into JSON shown below.

{
"appName": "PERFORMANCE",
"statsName": "Status Counts",
"DateBegin": "xxxxxx",
"DateEnd": "xxxxxxx",
"data": {
 "SUCCESS ": 1341,
"REJECT":5666,  "FAILURE":640,
 "ERROR":8515,
"TERMINATED":1447
}
}

I am new with XSLT stylesheets. Could anyone help me with the above problem? What is the XSLT stylesheet for converting the given XML to JSON?


Solution

  • You can use the following stylesheet. It works as desired for the given input XML:

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"  version="1.0">
    <xsl:output method="text" />
    
      <xsl:template match="/DATA">
          <xsl:text>{
        "appName": "PERFORMANCE",
        "statsName": "Status Counts",
        "DateBegin": "xxxxxx",
        "DateEnd": "xxxxxxx",
        "data": 
          </xsl:text>{&#xa;<xsl:apply-templates select="*" /><xsl:text>&#xa;}&#xa;}</xsl:text>
      </xsl:template>
    
      <xsl:template match="SUCCESS|REJECT|FAILURE|ERROR|TERMINATED">
        <xsl:value-of select="concat('&quot;',local-name(),'&quot;: ',COUNT___)" />
        <xsl:if test="position() != last()">,&#xa;</xsl:if>
      </xsl:template>
    
    </xsl:stylesheet>
    

    Its output is:

    {
    "appName": "PERFORMANCE",
    "statsName": "Status Counts",
    "DateBegin": "xxxxxx",
    "DateEnd": "xxxxxxx",
    "data": 
    {
    "SUCCESS": 5686,
    "REJECT": 641,
    "FAILURE": 8536,
    "ERROR": 1447,
    "TERMINATED": 1341
    }
    }
    

    The output doesn't match your desired output, because there were some inconsistencies between the input XML and the desired output XML. Change the XSLT according to your needs.