1

I want to convert JSON array into XML, but during conversion it generates invalid XML file:

String str = "{ 'test' : [ {'a' : 'A'},{'b' : 'B'}]}"; 
JSONObject json = new JSONObject(str);
String xml = XML.toString(json);

I used above code as suggested in Converting JSON to XML in Java

But if I tried to convert JSON object into XML it give invalid XML (error: The markup in the document following the root element must be well-formed.) which is

<test><a>A</a></test><test><b>B</b></test>

Can anybody please tell me how to get valid XML from JSON array or how to wrap JSON array while converting into XML?

Thanks in advance.

Community
  • 1
  • 1
PrashantP
  • 182
  • 1
  • 12

1 Answers1

3

XML documents can have only one root element. Your XML result is actually:

<test>
    <a>A</a>
</test>
<test>
    <b>B</b>
</test>

where the second test element is clearly after the document root element closing tag. XML.toString has a nice overload accepting object and string to enclose the result XML:

final String json = getPackageResourceString(Q43440480.class, "doc.json");
final JSONObject jsonObject = new JSONObject(json);
final String xml = XML.toString(jsonObject, "tests");
System.out.println(xml);

Now the output XML is well-formed:

<tests>
    <test>
        <a>A</a>
    </test>
    <test>
        <b>B</b>
    </test>
</tests>
Lyubomyr Shaydariv
  • 20,327
  • 12
  • 64
  • 105