Converting JSON to XML using XSLT without XML tag in JSON file

I need your help in converting JSON format into XML format using XSLT.

My JSON

{
    "SARIETransferRq": {
    "SARIETransferRqHeader": {
    "CorporateID": "ABCD0001",
    "CorpReferenceNumber": "4716936"
},
    "SARIETransferRqBody": {
    "AccountNumber": "02020202020",
    "DebitCurrency": "SAR",
    "Instructions2": "luaba",
    "Instructions3": "fadjiugu",
    "Instructions4": "rifdij",
    "Description": "sample description for service fee",
    "AMLPurposeCode": "BB"
}
},
  "Signature": {
    "SignatureValue": "sample"
  }
  }

Output XML:

<?xml version="1.0" encoding="UTF-8" ?>
 <root>
 <SARIETransferRq>
  <SARIETransferRqHeader>
  <CorporateID>ABCD0001</CorporateID>
  <CorpReferenceNumber>4716936</CorpReferenceNumber>
  </SARIETransferRqHeader>
   <SARIETransferRqBody>
  <AccountNumber>02020202020</AccountNumber>
  <DebitCurrency>SAR</DebitCurrency>
  <Instructions2>luaba</Instructions2>
  <Instructions3>fadjiugu</Instructions3>
  <Instructions4>rifdij</Instructions4>
  <Description>sample description for service fee</Description>
  <AMLPurposeCode>BB</AMLPurposeCode>
  </SARIETransferRqBody>
  </SARIETransferRq>
  <Signature>
  <SignatureValue>sample</SignatureValue>
  </Signature>
  </root>

In most of JSON to XML conversion i see there is xml tag in json file but my required doesn't have this XML tag in json file.

Can anyone suggest what needs to be corrected here:

Upvotes: 0

Views: 237

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167716

Assuming XSLT 3 where you start with a named template and pass in the JSON as a string parameter (you could use a file name/URI to the JSON file as well and make that param then <xsl:param name="json" select="unparsed-text('input.json')"/>)

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="3.0"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  exclude-result-prefixes="#all"
  expand-text="yes">

  <xsl:output method="xml" indent="yes" />

  <xsl:template match="/" name="xsl:initial-template">
    <root>
      <xsl:apply-templates select="json-to-xml($json)/*"/>
    </root>
  </xsl:template>
  
  <xsl:template match="*[@key]">
    <xsl:element name="{@key}">
      <xsl:apply-templates/>
    </xsl:element>
  </xsl:template>
  
  <xsl:param name="json" as="xs:string" expand-text="no">
{
    "SARIETransferRq": {
    "SARIETransferRqHeader": {
    "CorporateID": "ABCD0001",
    "CorpReferenceNumber": "4716936"
},
    "SARIETransferRqBody": {
    "AccountNumber": "02020202020",
    "DebitCurrency": "SAR",
    "Instructions2": "luaba",
    "Instructions3": "fadjiugu",
    "Instructions4": "rifdij",
    "Description": "sample description for service fee",
    "AMLPurposeCode": "BB"
}
},
  "Signature": {
    "SignatureValue": "sample"
  }
  }
  </xsl:param>

</xsl:stylesheet>

Online sample with SaxonJS.

Upvotes: 1

Related Questions