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.

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.