json-lib和dom4j实现JSON转XML

时间:2023-03-09 04:51:13
json-lib和dom4j实现JSON转XML
package com.geostar.gfstack.operationcenter.test;

import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper; /**
* Created by Administrator on 2017/6/13.
*/
public class TestJson2XML {
public static void main(String[] args) throws DocumentException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "wangrui");
jsonObject.put("age", "28");
System.out.println(json2Xml(jsonObject, "root"));
} public static String json2Xml(JSONObject json, String rootName) throws DocumentException {
String sXml = "";
XMLSerializer xmlSerializer = new XMLSerializer();
xmlSerializer.setTypeHintsEnabled(false);
xmlSerializer.setRootName(rootName);
String sContent = xmlSerializer.write(json);
try {
Document docCon = DocumentHelper.parseText(sContent);
sXml = docCon.getRootElement().asXML();
} catch (DocumentException e) {
e.printStackTrace();
}
return sXml;
}
}