How to convert XML to Json in XSLT?

How to convert xml to json in xslt

input xml:

<root>     <citiID>RR1</citiID>     <bib>ertyokf (5208). Free <Emphasis Type="Italic">of detachment</Emphasis>, aedrtg. dcdcdr<b>49</b> (2), 4185–428553. <a href="https://new.val/1991">1991</a>. <b>india</b>.</bib> </root> 

expected Json:

  "root": [     {         "citeid": "RR1",         "bib": "ertyokf (5208). Free <Emphasis Type=\"Italic\">of detachment</Emphasis>, aedrtg. dcdcdr<b>49</b> (2), 4185–428553. <a href="https://new.val/1991">1991</a>. <b>In india</b>."     },     ] 
Add Comment
3 Answer(s)

If you are using xslt3 there is a function for it,xml-to-json ()

This is explained here: Using XSLT 3.0 to transform XML

It can be done in xslt1 and 2 as well, but the approach is different – which version are you using?

Answered on July 16, 2020.
Add Comment

Note that the xml-to-json() function in XSLT 3.0 isn’t designed to handle arbitrary XML, it’s only designed to handle the "XML representation of JSON" produced by the json-to-xml() function.

You have two options: either transform your XML to a structure of maps and arrays and then serialize this as JSON, or transform it to the XML vocabulary that xml-to-json() accepts.

(The reason for this is well illustrated by your example, where you are trying to keep some of the elements represented as markup. No off-the-shelf conversion is going to do that for you.)

Also note: your expected output isn’t JSON. It needs surrounding curly braces to make it JSON: there’s also a stray comma that needs fixing.

I would do:

<xsl:template match="root">   <xsl:variable name="temp" as="map(*)" select="      map{ "root": [         map{ "citeID": string(citiID (:sic:)),              "bib": serialize(bib/child::node(), map{"method":"xml", "omit-xml-declaration": true()}         }]}"/>   <xsl:value-of select="serialize($temp, map{"method":"json", "indent":true()})"/> </xsl:template>   

Not tested.

Answered on July 16, 2020.
Add Comment

You can use two approaches, one is a direct representation of your desired JSON as XDM 3.1 maps and arrays:

<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 {         local-name() : array {           map:merge(* ! map {             lower-case(local-name()) : serialize(node())           })         }       }"/>   </xsl:template>    </xsl:stylesheet> 

https://xsltfiddle.liberty-development.net/naZYrpR/1

The second would be to transform your input XML into the XML representation of JSON the xml-to-json function uses.

Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.