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;
    }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM