package com.inspect.base.core.utils.json;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class XmlToJsonUtil {
    public static String xmlToJson(String xml) {
        try {
            Document doc = DocumentHelper.parseText(xml);
            Element rootEle = doc.getRootElement();
            JSONObject json = new JSONObject();
            dom4j2Json(rootEle, json);
            JSONObject resultJSON = new JSONObject();
            resultJSON.put(rootEle.getName(), json);
            return json.toJSONString();
        } catch (DocumentException e) {
            System.out.println("数据解析失败");
            e.printStackTrace();
            return null;
        }
    }

    public static JSONObject xmlToJsonObject(String xml) {
        try {
            System.out.println("------------待解析xml--------------" + xml);
            Document doc = DocumentHelper.parseText(xml);
            Element rootEle = doc.getRootElement();
            JSONObject json = new JSONObject();
            dom4j2Json(rootEle, json);
            return json;
        } catch (DocumentException e) {
            System.out.println("数据解析失败！");
            e.printStackTrace();
            return null;
        }
    }

    private static void dom4j2Json(Element element, JSONObject json) {

        for (Object o : element.attributes()) {
            Attribute attr = (Attribute) o;
            if (!isEmpty(attr.getValue())) {
                json.put(attr.getName(), attr.getValue());
            }
        }

        List<Element> childElements = element.elements();
        if (childElements.isEmpty() && !isEmpty(element.getText())) {
            json.put(element.getName(), element.getText());
        }


        for (Element e : childElements) {
            JSONObject jsonAttribute;
            Object o;
            JSONArray jsonArr;
            JSONObject jsonObj;
            if (e.elements().isEmpty()) {
                jsonAttribute = new JSONObject();

                for (Attribute attribute : e.attributes()) {
                    o = attribute;
                    Attribute attr = (Attribute) o;
                    if (!isEmpty(attr.getValue())) {
                        jsonAttribute.put(attr.getName(), attr.getValue());
                    }
                }

                if (!isEmpty(e.getText())) {
                    jsonAttribute.put(e.getName(), e.getText());
                }

                o = json.get(e.getName());
                if (o == null) {
                    if (!jsonAttribute.isEmpty()) {
                        json.put(e.getName(), jsonAttribute);
                    }
                } else {
                    jsonArr = null;
                    if (o instanceof JSONObject) {
                        jsonObj = (JSONObject) o;
                        json.remove(e.getName());
                        jsonArr = new JSONArray();
                        jsonArr.add(jsonObj);
                        jsonArr.add(jsonAttribute);
                    } else if (o instanceof JSONArray) {
                        jsonArr = (JSONArray) o;
                        jsonArr.add(jsonAttribute);
                    }

                    json.put(e.getName(), jsonArr);
                }
            } else {
                jsonAttribute = new JSONObject();
                dom4j2Json(e, jsonAttribute);
                o = json.get(e.getName());
                if (o == null) {
                    if (!jsonAttribute.isEmpty()) {
                        json.put(e.getName(), jsonAttribute);
                    }
                } else {
                    jsonArr = null;
                    if (o instanceof JSONObject) {
                        jsonObj = (JSONObject) o;
                        json.remove(e.getName());
                        jsonArr = new JSONArray();
                        jsonArr.add(jsonObj);
                        jsonArr.add(jsonAttribute);
                    } else if (o instanceof JSONArray) {
                        jsonArr = (JSONArray) o;
                        jsonArr.add(jsonAttribute);
                    }

                    json.put(e.getName(), jsonArr);
                }
            }
        }
    }

    public static boolean isEmpty(String str) {
        return str == null || str.trim().isEmpty() || "null".equals(str);
    }

    public static void main(String[] args) throws IOException {
        String xmlbook = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<customer>\n    <id>100</id>\n    <name>lanying</name>\n    <age>29</age>\n    <books>\n        <book>\n            <id>1</id>\n            <name>三国演义</name>\n            <price>100.0</price>\n        </book>\n        <book>\n            <id>2</id>\n            <name>红楼梦</name>\n        </book>\n        <book>\n            <id>1</id>\n            <price>100.0</price>\n        </book>\n        <book>\n            <name>西游记</name>\n            <price>50.0</price>\n        </book>\n    </books>\n</customer>";
        String pointModel = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n<Device_Model> \n<Item \nstation_name=\"变电站名称\" \nstation_id=\"变电站编码\" \nvideo_pos =\"关联视频编码及预置位\" /> \n<Item \nstation_name=\"变电站名称1\" \nstation_id=\"变电站编码1\" \nvideo_pos =\"关联视频编码及预置位1\" /> \n</Device_Model>";
        String pointModelxxx = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Device_Model>\n<Item station_name=\"变电站名称\" station_id=\"变电站编码\" /> \n</Device_Model>";
        String pointTest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Device_Model>\n    <Item station_name=\"变电站名称\" station_id=\"变电站编码\" area_id=\"区域 ID\" area_name=\"区域名称\" bay_id=\"间隔 ID\" bay_name=\"间隔名称\" main_device_id=\"503kaiguan\" main_device_name=\"主设备名称\" component_id=\"503kaiguan-daodianbufen\" component_name=\"部件名称\" device_id=\"503kaiguan-daodianbufen\" \n device_name=\"设备点位名称\" device_type=\"主设备类型\" meter_type=\"表计类型\" appearance_type=\"辅助设施类型\" \n save_type_list=\"采集/保存文件类型列表\" recognition_type_list=\"识别类型列表\" phase=\"相位\" device_info=\"备注信息\" \n data_type =\"设备点位支持的数据来源\" lower_value =\"1\" upper_value =\"2\" \n    video_pos ='[{\"device_code\":\"010010000103010001\",\"device_pos\":\"1\",\"robot_code\":\"010010000103010002\",\"robot_pos\":\"1\",\"uav_code\":\"010010000103010003\",\"uav_pos\":\"1\"},{\"device_code\":\"010010000103010001\",\"device_pos\":\"2\",\"robot_code\":\"010010000103010002\",\"robot_pos\":\"2\",\"uav_code\":\"010010000103010003\",\"uav_pos\":\"2\"}]' \n    />\n</Device_Model>";
        String pointTest1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Device_Model>\n    <Item station_name=\"变电站名称\" station_id=\"变电站编码\" area_id=\"区域 ID\" area_name=\"区域名称\" bay_id=\"间隔 ID\" bay_name=\"间隔名称\" main_device_id=\"主设备 ID\" main_device_name=\"主设备名称\" component_id=\"部件 ID\" component_name=\"部件名称\" device_id=\"设备点位 ID\" \n\tdevice_name=\"设备点位名称\" device_type=\"主设备类型\" meter_type=\"表计类型\" appearance_type=\"辅助设施类型\" \n\tsave_type_list=\"采集/保存文件类型列表\" recognition_type_list=\"识别类型列表\" phase=\"相位\" device_info=\"备注信息\" \n\tdata_type =\"设备点位支持的数据来源\" lower_value =\"1\" upper_value =\"2\" \n\tvideo_pos =\"[{\"device_code\":\"010010000103010001\",\"device_pos\":\"1\",\"robot_code\":\"010010000103010002\",\"robot_pos\":\"1\",\"uav_code\":\"010010000103010003\",\"uav_pos\":\"1\"},{\"device_code\":\"010010000103010001\",\"device_pos\":\"2\",\"robot_code\":\"010010000103010002\",\"robot_pos\":\"2\",\"uav_code\":\"010010000103010003\",\"uav_pos\":\"2\"}]\" \n\t />\n</Device_Model>";
        String pointTest2 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Device_Model>\n    <Item station_name=\"变电站名称\" station_id=\"变电站编码\" area_id=\"区域 ID\" area_name=\"区域名称\" bay_id=\"间隔 ID\" bay_name=\"间隔名称\" main_device_id=\"c5dbd4f4079c\" main_device_name=\"主设备名称\" component_id=\"c5dbd4f4079c-1\" component_name=\"部件名称\" device_id=\"设备点位 ID\" \n\tdevice_name=\"设备点位名称\" device_type=\"主设备类型\" meter_type=\"表计类型\" appearance_type=\"辅助设施类型\" \n\tsave_type_list=\"采集/保存文件类型列表\" recognition_type_list=\"识别类型列表\" phase=\"相位\" device_info=\"备注信息\" \n\tdata_type =\"设备点位支持的数据来源\" lower_value =\"1\" upper_value =\"2\" \n    video_pos =\"[{\"device_code\":\"010010000103010001\",\"device_pos\":\"1\",\"robot_code\":\"010010000103010002\",\"robot_pos\":\"1\",\"uav_code\":\"010010000103010003\",\"uav_pos\":\"1\"},{\"device_code\":\"010010000103010001\",\"device_pos\":\"2\",\"robot_code\":\"010010000103010002\",\"robot_pos\":\"2\",\"uav_code\":\"010010000103010003\",\"uav_pos\":\"2\"}]\" \n    />\n</Device_Model>";
        String s1 = pointTest.replaceAll("&", "&amp;");
        String stringJh = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Device_Model><Item station_name=\"变电站1\" station_code=\"1\" device_id=\"00E6C3FA119C43CBBF767631B8911BD7\" device_name=\"设备1红外普测\" bay_id=\"B253A3B61E624F72BBB23FF42975987C\" bay_name=\"间隔\" main_device_id=\"5DE69795AAA04C9B9882168E634DDAB3\" main_device_name=\"设备1\" device_type=\"25\" meter_type=\"\" appearance_type=\"\" save_type_list=\"fir\" recognition_type_list=\"4\" phase=\"\" device_info=\"\" component_id=\"4564D5FA221A4AD896B6199EDA072C18\" component_name=\"设备1-机器人设备部件\" area_name=\"区域\" area_id=\"CFED6A5DA0114FBD908737CD5C970684\" video_pos=\"[{&quot;robot_code&quot;:&quot;E100-0317&quot;,&quot;robot_pos&quot;:&quot;&quot;}]\"/><Item station_name=\"变电站1\" station_code=\"1\" device_id=\"E3E5593DB0084B41ABC466054B160DAD\" device_name=\"设备1缺陷\" bay_id=\"B253A3B61E624F72BBB23FF42975987C\" bay_name=\"间隔\" main_device_id=\"5DE69795AAA04C9B9882168E634DDAB3\" main_device_name=\"设备1\" device_type=\"25\" meter_type=\"\" appearance_type=\"\" save_type_list=\"jpg\" recognition_type_list=\"3\" phase=\"\" device_info=\"\" component_id=\"4564D5FA221A4AD896B6199EDA072C18\" component_name=\"设备1-机器人设备部件\" area_name=\"区域\" area_id=\"CFED6A5DA0114FBD908737CD5C970684\" video_pos=\"[{&quot;robot_code&quot;:&quot;E100-0317&quot;,&quot;robot_pos&quot;:&quot;&quot;}]\"/><Item station_name=\"变电站1\" station_code=\"1\" device_id=\"E9870E5CB97341D8B90E9C52C07531BB\" device_name=\"设备1可见光拍照\" bay_id=\"B253A3B61E624F72BBB23FF42975987C\" bay_name=\"间隔\" main_device_id=\"5DE69795AAA04C9B9882168E634DDAB3\" main_device_name=\"设备1\" device_type=\"25\" meter_type=\"\" appearance_type=\"1\" save_type_list=\"jpg\" recognition_type_list=\"3\" phase=\"\" device_info=\"\" component_id=\"4564D5FA221A4AD896B6199EDA072C18\" component_name=\"设备1-机器人设备部件\" area_name=\"区域\" area_id=\"CFED6A5DA0114FBD908737CD5C970684\" video_pos=\"[{&quot;robot_code&quot;:&quot;E100-0317&quot;,&quot;robot_pos&quot;:&quot;&quot;}]\"/><Item station_name=\"变电站1\" station_code=\"1\" device_id=\"47BEF5B6F34745A0A646C6F09EB42D4E\" device_name=\"设备2刀闸\" bay_id=\"B253A3B61E624F72BBB23FF42975987C\" bay_name=\"间隔\" main_device_id=\"96235E463C6F42DAB217E35A03CC82C7\" main_device_name=\"设备2\" device_type=\"25\" meter_type=\"\" appearance_type=\"1\" save_type_list=\"jpg\" recognition_type_list=\"2\" phase=\"\" device_info=\"\" component_id=\"E6EFD670DF8C4121BA83FC49165B757B\" component_name=\"设备2-机器人设备部件\" area_name=\"区域\" area_id=\"CFED6A5DA0114FBD908737CD5C970684\" video_pos=\"[{&quot;robot_code&quot;:&quot;E100-0317&quot;,&quot;robot_pos&quot;:&quot;&quot;}]\"/><Item station_name=\"变电站1\" station_code=\"1\" device_id=\"EDED73A6EE954B87BE28113A59448D96\" device_name=\"设备2指针\" bay_id=\"B253A3B61E624F72BBB23FF42975987C\" bay_name=\"间隔\" main_device_id=\"96235E463C6F42DAB217E35A03CC82C7\" main_device_name=\"设备2\" device_type=\"25\" meter_type=\"1\" appearance_type=\"\" save_type_list=\"jpg\" recognition_type_list=\"1\" phase=\"\" device_info=\"\" component_id=\"E6EFD670DF8C4121BA83FC49165B757B\" component_name=\"设备2-机器人设备部件\" area_name=\"区域\" area_id=\"CFED6A5DA0114FBD908737CD5C970684\" video_pos=\"[{&quot;robot_code&quot;:&quot;E100-0317&quot;,&quot;robot_pos&quot;:&quot;&quot;}]\"/></Device_Model>";
        String json1 = pointTest.replaceAll("\"device_code\":\"", "'device_code':'").replace("\"robot_code\":\"", "'robot_code':'").replace("\"uav_code\":\"", "'uav_code':'").replace("\"device_pos\":\"", "'device_pos':'").replace("\"robot_pos\":\"", "'robot_pos':'").replace("\"uav_pos\":\"", "'uav_pos':'");
        String json2 = json1.replaceAll("\",", "',").replace("\"}", "'");
        String pointJh = stringJh.replaceAll("\"\\[", "'\\[").replaceAll("]\"", "]'").replace("&quot;", "\"");
        JSONObject pointJhJsonObject = xmlToJsonObject(pointJh);
        Object o = pointJhJsonObject.get("Item");
        if (o instanceof JSONObject) {
            System.out.println(pointJhJsonObject);
        } else if (o instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) o;
            System.out.println(jsonArray);
        }

    }
}
