Vaibhav Tiwari
Vaibhav Tiwari

Reputation: 23

JSON to XML Conversion using XSLT

I have JSON returned from an API like below, where I want to fetch data of the latest date say 2022-01-13 in XML. Please can you guide me

daywisedata": {

        "2022-01-11": {
            "total_earning": 10,            
            "total_cost": 0
        },
        "2022-01-12": {
            "total_earning": 5,            
            "total_cost": 10
        },
        "2022-01-13": {
           "total_earning": 20,            
            "total_cost": 15
            }       
        }

XML needs to be returned like

 <daywisedata>
<total_earning> 20 </total_earning>            
<total_cost> 15 </total_cost> 
</daywisedata>

Upvotes: 1

Views: 202

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116992

Consider the following example:

XML (containing a valid(!) JSON)

<JSON>
{
    "daywisedata" : 
    {
        "2022-01-11" : 
        {
            "total_cost" : 0,
            "total_earning" : 10
        },
        "2022-01-12" : 
        {
            "total_cost" : 10,
            "total_earning" : 5
        },
        "2022-01-13" : 
        {
            "total_cost" : 15,
            "total_earning" : 20
        }
    }
}
</JSON>

XSLT 3.0

<xsl:stylesheet version="3.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>

<xsl:template match="/">
    <xsl:variable name="map" select="parse-json(JSON)?daywisedata?*[last()]" />
    <results>
        <total_cost>
            <xsl:value-of select="$map?total_cost"/>
        </total_cost>
        <total_earning>
            <xsl:value-of select="$map?total_earning"/>
        </total_earning>
    </results>
</xsl:template>

</xsl:stylesheet>

Result

<?xml version="1.0" encoding="UTF-8"?>
<results>
   <total_cost>15</total_cost>
   <total_earning>20</total_earning>
</results>

Demo: https://xsltfiddle.liberty-development.net/3MXNWNB

Upvotes: 1

Related Questions