How to Convert JSON to XML using XSLT 2.0

XSLT 2.0 is powerful enough to process even non-XML input. For example, I have created a transformation that converts JSON text to well structured XML output:

JSON text:

{
     "firstName": "John",
     "lastName": "Smith",
     "age": 25,
     "address": {
         "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postalCode": "10021"
     },
     "phoneNumber": [
         { "type": "home", "number": "212 555-1234" },
         { "type": "fax", "number": "646 555-4567" }
     ]
}

XML result:

 <?xml version="1.0" encoding="UTF-8"?>
<json>
   <object>
      <field name="firstName">
         <string>John</string>
      </field>
      <field name="lastName">
         <string>Smith</string>
      </field>
      <field name="age">
         <number>25</number>
      </field>
      <field name="address">
         <object>
            <field name="streetAddress">
               <string>21 2nd Street</string>
            </field>
            <field name="city">
               <string>New York</string>
            </field>
            <field name="state">
               <string>NY</string>
            </field>
            <field name="postalCode">
               <string>10021</string>
            </field>
         </object>
      </field>
      <field name="phoneNumber">
         <array>
            <object>
               <field name="type">
                  <string>home</string>
               </field>
               <field name="number">
                  <string>212 555-1234</string>
               </field>
            </object>
            <object>
               <field name="type">
                  <string>fax</string>
               </field>
               <field name="number">
                  <string>646 555-4567</string>
               </field>
            </object>
         </array>
      </field>
   </object>
</json>

It works by employing XML Pipeline technique:

  • first mode parses text using regular expressions and generates sequence of tokens in XML format: <comment>, <string>, <number>, <symbol>{</symbol>, etc.
  • second mode groups all tokens between "{" and "}" symbols into <object> element, between "[" and "]" symbols into <array> element
  • third mode makes a <field> element from <string><symbol>:<symbol>(<string>|<number>|<object>|<array>) sequence
  • fourth mode drops comma between consecutive <field> elements

and finally it performs XSD validation check.

This approach is quite exotic and non-standard, because when people hear word "parsing" they think of BNF, state-machine, AST, YACC, etc., but these technologies were created to parse complex programming languages.

I claim that XSLT coupled w/ regexp as tokenizer is powerful enough to convert simple markup languages such as JSON, CSS, MIF, RTF, wiki, etc., into XML.

p.s.
See attachment below for source code of the transformation.

AttachmentSize
json2xml.zip5.13 KB

Comments

Error with this xslt

I am trying to use this source code, but the .xsl file is not compiled saying

line 18: Unsupported XSL element 'analyze-string'

Can you please help on htis!

Thanks,

The exception is thrown from

The exception is thrown from JsonToXml.java

TransformerHandler handler = handlerFactory.newTransformerHandler(new StreamSource(JsonToXml.class.getResource("./json2xml.xsl").toString()));

and the stacktrace is as following:

Compiler warnings:
line 59: Illegal attribute 'select'.
line 65: Illegal attribute 'select'.
ERROR: 'line 18: Unsupported XSL element 'analyze-string'.'
FATAL ERROR: 'Could not compile stylesheet'
Exception in thread "main" javax.xml.transform.TransformerConfigurationException: Could not compile stylesheet
at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl.newTemplates(Unknown Source)
at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl.newTransformer(Unknown Source)
at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl.newTransformerHandler(Unknown Source)
at utility.jsontosoap.JsonToXml.json2xml(JsonToXml.java:37)
at utility.jsontosoap.JsonToXml.main(JsonToXml.java:31)

json2xml is XSLT 2.0

json2xml is XSLT 2.0 transform, the stacktrace indicates default TrAX processor (Xalan) is invoked, but Xalan is not XSLT 2.0 processor.

To get json2xml running, you need XSLT 2.0 processor, for example, such as Saxon – check lib/readme.txt:

grab Saxon-HE 9.2.1.1 from http://www.saxonica.com/ unpack saxon9he.jar here

thanks Andriy Gerasika, it

thanks Andriy Gerasika, it worked after getting saxon :)

hello, i wanted to use this

hello, i wanted to use this app.
in the xsl, you are inserting 'array' or 'object' based on conditions (w.r.t. the json.xsd). but i want to use my own run time generated strings instead of such predefined values. is there any way to do this?

also this xsl is generating various empty text nodes after each xml node. how can i get rid of this?

thanks!

It is all possible

1. If you want to transform JSON to your own XML model, you should write 2nd XSLT transformation, transforming from my JSON.XSD to required format.

2. To get rid of empty text nodes, use xsl:output element with indent="no" attribute

JSon element value is null

Hi,
If the input JSON has null value then the following error is thrown while transforming JSON to XML. (For Example -= "middleName": null )

Error Message :
unknown token: null
error at line: 74 col:27 message: cvc-complex-type.2.4.a: Invalid content was found starting with element 'symbol'. One of '{field}' is expected.

Thanks
Siva

fixed & refreshed attachment

fixed & refreshed attachment w/ newer version (it may take 24 hours to update at your location)

new version

if you plan to use json2xml XSLT in real world applications, I recommend using code from my new article How to Convert JSON to XML using ANTLR

Post new comment

The content of this field is kept private and will not be shown publicly.