Search code examples
jsonxmlxsltxslt-2.0xslt-3.0

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> any text</bib>
</root>

expected Json:

  "root": [
    {
        "citeid": "RR1",
        "bib": "ertyokf (5208). Free <Emphasis Type=\"Italic\">of detachment</Emphasis>, aedrtg. dcdcdr<b>49</b> any text."
    },
    ]

Solution

  • 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.