Currently I need to convert json to xml and xml to json vice versa using XSLT 3.0 & Saxon-HE.
Below is my json abc.xml file
<?xml version="1.0" encoding="UTF-8" ?>
<root>
<data>{
"cars" : [
{"doors" : "4","price" : "6L"},
{"doors" : "5","price" : "13L"}
]
}
</data>
</root>
Below is xsl file xyz.xsl
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:math="http://www.w3.org/2005/xpath-functions/math"
exclude-result-prefixes="xs math"
version="3.0">
<xsl:output indent="yes"/>
<xsl:template match="data">
<xsl:copy-of select="json-to-xml(.)"/>
</xsl:template>
Below is output xml
<?xml version="1.0" encoding="UTF-8"?>
<map xmlns="http://www.w3.org/2005/xpath-functions">
<array key="cars">
<map>
<string key="doors">4</string>
<string key="price">6L</string>
</map>
<map>
<string key="doors">5</string>
<string key="price">13L</string>
</map>
</array>
</map>
Now My Question is how i can get back the same json from the output.xml? I am trying this using xslt function xml-to-json() but the output format is looking incorrect. Below is the xsl and output m getting.
123.xsl
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:math="http://www.w3.org/2005/xpath-functions/math"
exclude-result-prefixes="xs math"
version="3.0">
<xsl:output indent="yes"/>
<xsl:template match="data">
<xsl:copy-of select="xml-to-json(.)"/>
</xsl:template>
</xsl:stylesheet>
Output JSon
Try this example here https://xsltfiddle.liberty-development.net/3NzcBsQ
In xsl I am selecting wrong template named data. because data template is not in output.xml. I am not sure what should i write here.
<xsl:template match="data">
<xsl:value-of select="xml-to-json(.)"/>
with your XML the output is{"cars":[{"doors":"4","price":"6L"},{"doors":"5","price":"13L"}]}
. – Foofaraw