XSLT Transformation Mapping

34 views Asked by At

I want to transform the below source to target using XSLT, but unable to do so. Could you please help on it?

Source :

{
  "gp_number" : "56826526",
  "lineLevel" : [ {
    "Qty" : "4.00",
    "Rate" : "50.00"
  }, {
    "Qty" : "3.00",
    "Rate" : "25.00"
  } ]
}

Target:

{
  "gp_number" : "56826526",
  "AmountCal_line" : [ {
    "Qty" : "4.00",
    "Rate" : "50.00",
    "Amount" : "200.00"
  }, {
    "Qty" : "3.00",
    "Rate" : "25.00",
    "Amount" : "75.00"
  } ],
  "TotalAmount" : "275.00"
}
1

There are 1 answers

0
Martin Honnen On

With XSLT 3, as supported by current versions of SaxonJS (2.6 is the current version) or Saxon Java, SaxonC, Saxon .NET or SaxonCS, you can process JSON input (on the command line with option -json) and produce JSON output (with XDM maps and arrays being serialized with output method json):

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:map="http://www.w3.org/2005/xpath-functions/map"
    exclude-result-prefixes="#all"
    version="3.0">
    
    <xsl:output method="json" indent="yes"/>
   
    <xsl:template match=".">
      <xsl:sequence 
        select="map { 'gp_number' : ?gp_number,
                      'lineLevel' : array { ?lineLevel?* ! map:put(., 'Amount', xs:decimal(?Qty) * xs:decimal(?Rate)) },
                      'Total_Amount' : sum(?lineLevel?*!(xs:decimal(?Qty) * xs:decimal(?Rate)))
                }"/>
    </xsl:template>
    
</xsl:stylesheet>

Example fiddle using SaxonJS 2.