package com.yeejoin.precontrol.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.thoughtworks.xstream.XStream;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @Description: TODO
 * @Author: Wanglulu
 * @Date: 2021/7/27 16:08
 * @Version 0.0.1
 */
public class XmlUtil {

    /*
     * xml转map
     */
    public static JSONObject xmlToMap(HttpServletRequest request) throws IOException, DocumentException {
        JSONObject map = new JSONObject();
        SAXReader reader = new SAXReader();
        InputStream ins = request.getInputStream();
        Document doc = reader.read(ins);
        Element root = doc.getRootElement();
        @SuppressWarnings("unchecked")
        List<Element> list = (List<Element>) root.elements();
        for (Element e : list) {
            map.put(e.getName(), e.getText());
        }
        ins.close();
        return map;
    }

    /**
     * xml详细信息解析
     */
    public static JSONObject xmlToMap(String xml) throws DocumentException {
        JSONObject json = new JSONObject();
        Document doc = DocumentHelper.parseText(xml);
        Element root = doc.getRootElement();
        Iterator it = root.elementIterator();
        while (it.hasNext()) {
            Element element = (Element) it.next();
            json.put(element.getName(), element.getTextTrim());
        }
        return json;
    }
}
