Renganathan V
Renganathan V

Reputation: 523

Converting JSON to XML using XSLT

Following is my requirement:

Application A is creating a JSON based on its Java Beans and sending to my Application. I have to take this JSON and convert it into XML (XSD for this is completely different than my JSON structure) and send to Application B.

Solution 1) I am currently converting this json to xml using json.org library.Then using Apache-xalan and XSL stylesheet, I am converting this to xml format as required by App B.

Solution 2) Converting this json to Java Bean (JB1).Then converting this JB1 to another Java Bean (JB2) as per the xml structure required by Application B.Then convert JB2 to XML for app B.

Solution 3) Using Apache Xalan and Xerces to parse through the input json and make the XML in Java itself without using XSL.

Which is better approach (in simplicity of code, throughput )? As JSON becomes more complex, is it easy to use solution 1 ? Please suggest if there is better approach other than these 3 ?

Upvotes: 0

Views: 2293

Answers (4)

Michael Kay
Michael Kay

Reputation: 163585

XSLT 3.0 offers a built-in json-to-xml() function. Once you have the XML, you can easily transform it to your required format. It is implemented in Saxon 9.7 (PE or higher) and I believe in Exselt.

Upvotes: 2

kjhughes
kjhughes

Reputation: 111726

Solution 1: Yes. This is the conventional and best path for both simple and complex JSON and simple or complex targeted XML.

Solution 2: No. There's no reason to introduce Java Beans as an intermediate form, especially if you have no other need for Java Beans. This option unnecessarily introduces transformational and marshalling complexity.

Solution 3: No. Neither Xalan nor Xerces are designed to parse JSON; they are designed to parse XML.

Upvotes: 1

keshlam
keshlam

Reputation: 8058

There are sample programs that will map a JSON document into an equivalent XML document and back; I wrote one as a demo for Liberty's support of json-p (javax.json), using an XML vocabulary I called JinX (JSON in XML). That could be used as a pre/post processor wrapped around XSLT, if desired.

Better solutions are possible -- redefine XSLT to operate on JSON trees, for example -- but would take a bit more work.

Upvotes: 0

Mike Robinson
Mike Robinson

Reputation: 8995

JSON is, pure-and-simple, "a communications protocol." In other words, "it specifically exists(!) to allow 'arbitrary (JavaScript) data structures' to be conveyed between some-client and some-host," over "the HTTP(S) protocol."

Therefore: "it is not(!) XML," and therefore must never be considered to be "appropriate input to XSLT!"

"Thou shalt not mix Apples and Oranges!"

If you wish to apply "XSLT" technologies to a "JSON-derived" input (which is, by definition, "a data structure ...") then you must first, and "by whatever suitable means," convert that data structure into XML.

Upvotes: -2

Related Questions