Marco Dinatsoli
Marco Dinatsoli

Reputation: 10570

java add a root element to a xml document

I have a JSON string array coming from a simple JSON library, and I want to create an XML for that string.

i did this using json.org library.

org.json.JSONArray jsonObject = new org.json.JSONArray(giveJson());
        return XML.toString(jsonObject);

where giveJSON is a function to give me the string of a JSON array. my problem is that the resulting xml is from this style:

<array>
</array>
<array>
</array>

it has no root element and as you know without a root element, the xml becomes invalid to most of the libraries specially iOS library. help me please to add a root to that xml string

Upvotes: 0

Views: 2000

Answers (2)

Ashraf Sarhan
Ashraf Sarhan

Reputation: 1697

You can wrap your xml format for the given json under specific xml root tag using the following method from org.json library.

JSONObject rootObject= new JSONObject();
rootObject.put("root", <YOUR_JSONARRAY>);
XML.toString(rootObject, "rootTag");

Upvotes: 3

Rahul Yadav
Rahul Yadav

Reputation: 1513

You can add your JSONArray to JSONObject by creating an instance of JSONObject as below:-

JSONObject rootObject= new JSONObject();
rootObject.put("root", <YOUR_JSONARRAY>);

Upvotes: 1

Related Questions