package com.diaoyun.zion.master.util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

import java.io.IOException;
import java.io.StringWriter;


/**
 * 处理 XML 文件格式的工具类
 *
 * @author 爱酱油不爱醋
 */
public class XmlUtils {

    /**
     * 将 xml 格式的数据转换为 Json 格式
     * @param xml xml 格式的字符串
     * @return Json 格式的字符串
     */
    public static String convertXmlIntoJSONObject(String xml) {
        JSONObject jsonObject = new JSONObject();
        try {
            Document xmlDocument = DocumentHelper.parseText(xml);
            OutputFormat format = new OutputFormat();
            format.setEncoding("UTF-8");
            format.setExpandEmptyElements(true);
            StringWriter out = new StringWriter();
            XMLWriter writer = new XMLWriter(out, format);
            try {
                writer.write(xmlDocument);
                writer.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //out.toString() 此结果为xml的<a></a>格式
            jsonObject = XML.toJSONObject(out.toString());
        } catch (DocumentException e1) {
            e1.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject.toString();
    }
}
