I want to convert JSON array into XML, but during conversion it generates invalid XML file:
我想将JSON数组转换为XML,但在转换过程中它会生成无效的XML文件:
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
我使用上面的代码,如在Java中将JSON转换为XML中所建议的那样
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
但是,如果我尝试将JSON对象转换为XML,则会产生无效的XML(错误:根元素后面的文档中的标记必须格式正确。)这是
<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?
任何人都可以告诉我如何从JSON数组获取有效的XML或如何在转换为XML时包装JSON数组?
Thanks in advance.
提前致谢。
1 个解决方案
#1
2
XML documents can have only one root element. Your XML result is actually:
XML文档只能有一个根元素。您的XML结果实际上是:
<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:
其中第二个测试元素明显位于文档根元素结束标记之后。 XML.toString有一个很好的重载接受对象和字符串来包含结果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:
现在输出XML格式正确:
<tests>
<test>
<a>A</a>
</test>
<test>
<b>B</b>
</test>
</tests>
#1
2
XML documents can have only one root element. Your XML result is actually:
XML文档只能有一个根元素。您的XML结果实际上是:
<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:
其中第二个测试元素明显位于文档根元素结束标记之后。 XML.toString有一个很好的重载接受对象和字符串来包含结果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:
现在输出XML格式正确:
<tests>
<test>
<a>A</a>
</test>
<test>
<b>B</b>
</test>
</tests>