使用 org.json json 库,可以轻松地将 XML 转换为 JSON。但是转换回 XML 总是将 JSON 属性转换为 XML 节点:
import org.json.JSONObject;
import org.json.XML;
public class Test {
public static void main(String[] args) throws Exception {
String xml = "<tag1 attr1=\"val1\"><tag2 attr2=\"val2\"/></tag1>";
System.out.println(xml);
JSONObject str = XML.toJSONObject(xml);
System.out.println(str);
JSONObject json = new JSONObject(str.toString());
String xml2 = XML.toString(json);
System.out.println(xml2);
}
}
输出
<tag1 attr1="val1"><tag2 attr2="val2"/></tag1>
{"tag1":{"attr1":"val1","tag2":{"attr2":"val2"}}}
<tag1><attr1>val1</attr1><tag2><attr2>val2</attr2></tag2></tag1>
如何检索我的 XML 属性?
最佳答案
Underscore-java有静态方法 U.xmlToJson(xml)
和 U.jsonToXml(json)
。 Live example
import com.github.underscore.U;
public class Test {
public static void main(String[] args) {
String xml = "<tag1 attr1=\"val1\"><tag2 attr2=\"val2\"/></tag1>";
System.out.println(U.xmlToJson(xml));
System.out.println(U.jsonToXml(U.xmlToJson(xml)));
}
}
// {
// "tag1": {
// "-attr1": "val1",
// "tag2": {
// "-attr2": "val2",
// "-self-closing": "true"
// }
// },
// "#omit-xml-declaration": "yes"
// }
关于Java - 将 JSON 转换为 XML 并保持属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38002128/