cancel
Showing results for 
Search instead for 
Did you mean: 

JAVA mapping for well formed XML

Former Member
0 Kudos

Dear Experts,

I am trying to convert JSON data to XML with the below code which was shared by Hareesh. It works

fine with single item record but when multiple items are there , it doesn't form well formed XML structure.It gives multiple root element.


                                                            Code

import java.io.BufferedReader;

import java.io.InputStream;

import java.io.InputStreamReader;

import org.json.JSONObject;

import com.sap.aii.mapping.api.AbstractTransformation;

import com.sap.aii.mapping.api.StreamTransformationException;

import com.sap.aii.mapping.api.TransformationInput;

import com.sap.aii.mapping.api.TransformationOutput;

public class xml2json extends AbstractTransformation {

public void transform(TransformationInput in, TransformationOutput out) throws StreamTransformationException {

    try {

  String sourcexml = ""; String targetxml =""; String line ="";

  InputStream ins =    in.getInputPayload().getInputStream();

  BufferedReader br = new BufferedReader( new InputStreamReader(ins));

  while ((line = br.readLine()) != null)

  sourcexml +=line+"\n";

  br.close();

  JSONObject o = new JSONObject(sourcexml);

  targetxml = org.json.XML.toString(o);

  out.getOutputPayload().getOutputStream().write(targetxml.getBytes());

    }

    catch (Exception e) {

           throw new StreamTransformationException(e.getMessage());

  }

}

}


                                                                               Payload

{

    "items": [

        {

            "item": {

                "Subject": "test wared by wael",

                "DocumentID": "55DCE0A476D",

                "Sender": "Rebecca",

                "SenderDomainName": "user1",

                "Date": "2013-02-14 11:14:40",

                "DocumentClassID": "11"

            }

        },

        {

            "item": {

                "Subject": "test wared by wael",

                "DocumentID": "55DCE191D5E47",

                "Sender": "Dave Froster",

                "SenderDomainName": "user11",

                "Date": "2013-03-14 11:14:40",

                "DocumentClassID": "11"

            }

        }

    ]

}

What line of code can be added so that the XML result comes with XML declaration and with 1 root node.

Regards..

Accepted Solutions (1)

Accepted Solutions (1)

iaki_vila
Active Contributor
0 Kudos

Hi Rebecca,

Check this blog. it can be helpful to deal with JSON arrays: Java crumbs » Blog Archive » Converting JSON to XML

Hope this helps.

Regards.

Answers (1)

Answers (1)

former_member184720
Active Contributor
0 Kudos

You can even simply append a root tag to the "targetxml"

targetxml = org.json.XML.toString(o);

targetxml = "<root>"+targetxml+"</root>";