All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.founder.utils.XmlUtils Maven / Gradle / Ivy

The newest version!
package com.founder.utils;

import com.alibaba.fastjson.JSON;
import com.founder.core.log.MyLog;
import com.founder.core.vopackage.VoJytBaseDTO;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class XmlUtils {

    private static final MyLog _log = MyLog.getLog(XmlUtils.class);

    /**
     *
     * @param clazz
     *            类的字节码文件
     * @param xml
     *            传入的XML字符串
     * @return XML字符串转实体类
     */
    public static  T parseFromXml(Class clazz, String xml) {
        XStream xStream = new XStream(new DomDriver());
        xStream.ignoreUnknownElements();
        xStream.processAnnotations(clazz);
        xStream.allowTypes(new Class[]{clazz});
        @SuppressWarnings("unchecked")
        T t = (T) xStream.fromXML(xml);
        return t;
    }

    public static  T parseFromXml(Class[] clazz, String xml) {
        XStream xStream = new XStream(new DomDriver());
        xStream.ignoreUnknownElements();
        xStream.processAnnotations(clazz);
        xStream.autodetectAnnotations(true);
        xStream.allowTypes(clazz);
        @SuppressWarnings("unchecked")
        T t = (T) xStream.fromXML(xml);
        return t;
    }

    /**
     *
     *
     * @param obj
     *            实体类
     * @return 实体类转XML字符串
     */
    public static String toXml(Object obj) {
        XStream xStream = new XStream(new DomDriver());
        // 扫描@XStream注解
        xStream.processAnnotations(obj.getClass());
        xStream.autodetectAnnotations(true);
        xStream.aliasSystemAttribute(null, "class"); // 去掉 class 属性
        String xml = xStream.toXML(obj).replaceAll("\\_+", "_");//正则过滤双下划线转为单下划线
        xml = "" + xml;
        return xml;
    }

    public static List xml2listWithAttr(String xmlStr) throws DocumentException {
        List listm = new ArrayList<>();
        Document doc = DocumentHelper.parseText(xmlStr);
        Element root = doc.getRootElement();
        Element inputsdata = root.element("BODY").element("N_INPUT").element("DATA").element("INPUTS");
        for(Iterator it=inputsdata.elementIterator();it.hasNext();){
            Map map =new HashMap();
            Element element = (Element) it.next();
            for(Iterator it2=element.elementIterator();it2.hasNext();) {
                Element element1 = (Element) it2.next();
                map.put(element1.getName(),element1.getText());
            }
            listm.add(map);
        }
        _log.info(listm.size()+"***");
        return listm;
    }

    public static String buildXml(VoJytBaseDTO jytBaseDTO, List listMap) throws DocumentException {
        String xmlStr = XmlUtils.toXml(jytBaseDTO);
        Document doc = DocumentHelper.parseText(xmlStr);
        Element root = doc.getRootElement();
        Element outputsdata = root.element("BODY").element("N_OUTPUT").element("DATA").addElement("OUTPUTS");
        for (Map listMap1 : listMap) {
            Iterator iter = listMap1.keySet().iterator();
            Element outputdata = outputsdata.addElement("OUTPUT");
            while (iter.hasNext()) {
                String key = iter.next();
                String value = "";
                if (listMap1.get(key) != null) {
                    value = listMap1.get(key).toString();
                }
                _log.debug("打印:" + key+"***"+value);
                outputdata.addElement(key).setText(StringUtils.isBlank(listMap1.get(key).toString())?"":listMap1.get(key).toString());
            }
        }
        return doc.asXML();
    }

    /**
     * 构建返回xml
     * @param operateMap
     * @param resultMap
     * @param row
     * @return
     */
    public static String buildXml(Map operateMap, Map resultMap, String row) {
        try {
            Document document = DocumentHelper.parseText(Constant.BUSINESS_XML_TEMP);
            String datarow = "" + row + "";
            Document documentRow = DocumentHelper.parseText(datarow);
            documentRow.setXMLEncoding("gb2312");
            Element operateElement = document.getRootElement().element("operateinfo").addElement("info");
            operateMap.forEach((k, v) -> {
                operateElement.addAttribute(k, v);
            });
            Element resultElement = document.getRootElement().element("result").addElement("info");
            resultMap.forEach((k, v) -> {
                resultElement.addAttribute(k, v);
            });
            document.getRootElement().element("returndata").add(documentRow.getRootElement());
            _log.debug(document.asXML());
            return document.asXML();
        } catch (DocumentException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 构建返回xml 传入returndata节点数据(map)
     * @param operateMap
     * @param resultMap
     * @param returnMap
     * @return
     */
    public static String buildXml(Map operateMap, Map resultMap, Map returnMap) {
        try {
            Document document = DocumentHelper.parseText(Constant.BUSINESS_XML_TEMP);
            Element operateElement = document.getRootElement().element("operateinfo").addElement("info");
            operateMap.forEach((k, v) -> {
                operateElement.addAttribute(k, v);
            });
            Element resultElement = document.getRootElement().element("result").addElement("info");
            resultMap.forEach((k, v) -> {
                resultElement.addAttribute(k, v);
            });
            Element returnElement = document.getRootElement().element("returndata").addElement("data").addElement("datarow");
            returnMap.forEach((k, v) -> {
                returnElement.addAttribute(k, v);
            });
            return document.asXML();
        } catch (DocumentException e) {
            e.printStackTrace();
            return null;
        }
    }

    /*private static Element map2xml(Map map, Element body) {
        Iterator> entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry entry = entries.next();
            String key = entry.getKey();
            Object value = entry.getValue();
            if (key.startsWith("@")) {    //属性
                body.addAttribute(key.substring(1, key.length()), value.toString());
            } else if (key.equals("#text")) { //有属性时的文本
                body.setText(value.toString());
            } else {
                if (value instanceof List) {
                    List list = (List) value;
                    Object obj;
                    for (int i = 0; i < list.size(); i++) {
                        obj = list.get(i);
                        //list里是map或String,不会存在list里直接是list的,
                        if (obj instanceof Map) {
                            Element subElement = body.addElement(key);
                            map2xml((Map) list.get(i), subElement);
                        } else {
                            body.addElement(key).setText((String) list.get(i));
                        }
                    }
                } else if (value instanceof Map) {
                    Element subElement = body.addElement(key);
                    map2xml((Map) value, subElement);
                } else {
                    body.addElement(key).setText(value.toString());
                }
            }
            //System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
        }
        return body;
    }*/

    /*public static String formatXml(String xmlStr) throws DocumentException, IOException {
        Document document = DocumentHelper.parseText(xmlStr);
        return document.getRootElement().asXML();//formatXml(document);
    }*/

    /*public static String formatXml(Document document) throws DocumentException, IOException {
        // 格式化输出格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        //format.setEncoding("UTF-8");
        StringWriter writer = new StringWriter();
        // 格式化输出流
        XMLWriter xmlWriter = new XMLWriter(writer, format);
        // 将document写入到输出流
        xmlWriter.write(document);
        xmlWriter.close();
        return writer.toString();
    }*/

    /**
     * String 转 org.dom4j.Document
     *
     * @param xml
     * @return
     * @throws DocumentException
     */
    /*public static Document strToDocument(String xml) throws DocumentException {
        return DocumentHelper.parseText(xml);
    }*/

    /**
     * org.dom4j.Document 转  com.alibaba.fastjson.JSONObject
     *
     * @param xml
     * @return
     * @throws DocumentException
     */
    /*public static JSONObject documentToJSONObject(String xml) throws DocumentException {
        return elementToJSONObject(strToDocument(xml).getRootElement());
    }*/

    /**
     * org.dom4j.Element 转  com.alibaba.fastjson.JSONObject
     *
     * @param
     * @return
     */
    /*public static JSONObject elementToJSONObject(Element node) {
        JSONObject result = new JSONObject();
        // 当前节点的名称、文本内容和属性
        List listAttr = node.attributes();// 当前节点的所有属性的list
        for (Attribute attr : listAttr) {// 遍历当前节点的所有属性
            result.put(attr.getName(), attr.getValue());
        }
        // 递归遍历当前节点所有的子节点
        List listElement = node.elements();// 所有一级子节点的list
        if (!listElement.isEmpty()) {
            for (Element e : listElement) {// 遍历所有一级子节点
                if (e.attributes().isEmpty() && e.elements().isEmpty()) // 判断一级节点是否有属性和子节点
                    result.put(e.getName(), e.getTextTrim());// 沒有则将当前节点作为上级节点的属性对待
                else {
                    if (!result.containsKey(e.getName())) // 判断父节点是否存在该一级节点名称的属性
                        result.put(e.getName(), new JSONArray());// 没有则创建
                    ((JSONArray) result.get(e.getName())).add(elementToJSONObject(e));// 将该一级节点放入该节点名称的属性对应的值中
                }
            }
        }
        return result;
    }*/

    //map转xml huql
    /*public static String callMapToXML(Map map) {
        _log.info("将Map转成Xml, Map:" + map.toString());
        StringBuffer sb = new StringBuffer();
        sb.append("");
        mapToXMLTest2(map, sb);
        sb.append("");
        _log.info("将Map转成Xml, Xml:" + sb.toString());
        try {
            return sb.toString();
        } catch (Exception e) {
            _log.error("将Map转成Xml失败" + e.getMessage());
        }
        return null;
    }*/

    /*private static void mapToXMLTest2(Map map, StringBuffer sb) {
        Set set = map.keySet();
        for (Iterator it = set.iterator(); it.hasNext(); ) {
            String key = (String) it.next();
            Object value = map.get(key);
            if (null == value)
                value = "";
            if (value.getClass().getName().equals("java.util.ArrayList")) {
                ArrayList list = (ArrayList) map.get(key);
                sb.append("<" + key + ">");
                for (int i = 0; i < list.size(); i++) {
                    HashMap hm = (HashMap) list.get(i);
                    mapToXMLTest2(hm, sb);
                }
                sb.append("");

            } else {
                if (value instanceof HashMap) {
                    sb.append("<" + key + ">");
                    mapToXMLTest2((HashMap) value, sb);
                    sb.append("");
                } else {
                    sb.append("<" + key + ">" + value + "");
                }

            }

        }
    }*/

    public static Map xml2map(String xmlStr) throws DocumentException {
        Map map = new HashMap<>(10);
        try {
            Document doc = DocumentHelper.parseText(xmlStr);
            Element infoElement = doc.getRootElement().element("result").element("info");
            infoElement.attributes().stream().forEach(x->{Attribute element = (Attribute)x;
                map.put(element.getName(), element.getStringValue());});
        } catch (DocumentException e) {
            e.printStackTrace();
            map.put("execute_flag", "-1");
        }


        return map;
    }

        /*public static Document map2xml(Map map, String rootName) throws DocumentException, IOException {
        Document doc = DocumentHelper.createDocument();
        Element root = DocumentHelper.createElement(rootName);
        doc.add(root);
        map2xml(map, root);
        return doc;
    }*/

    /*public static Document map2xml(Map map) throws DocumentException, IOException {
        Iterator> entries = map.entrySet().iterator();
        if (entries.hasNext()) { //获取第一个键创建根节点
            Map.Entry entry = entries.next();
            Document doc = DocumentHelper.createDocument();
            Element root = DocumentHelper.createElement(entry.getKey());
            doc.add(root);
            map2xml((Map) entry.getValue(), root);
            return doc;
        }
        return null;
    }*/

    /*private static Map xml2map(Element e) {
        Map map = new LinkedHashMap();
        List list = e.elements();
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                Element iter = (Element) list.get(i);
                List mapList = new ArrayList();

                if (iter.elements().size() > 0) {
                    Map m = xml2map(iter);
                    if (map.get(iter.getName()) != null) {
                        Object obj = map.get(iter.getName());
                        if (!(obj instanceof List)) {
                            mapList = new ArrayList();
                            mapList.add(obj);
                            mapList.add(m);
                        }
                        if (obj instanceof List) {
                            mapList = (List) obj;
                            mapList.add(m);
                        }
                        map.put(iter.getName(), mapList);
                    } else
                        map.put(iter.getName(), m);
                } else {
                    if (map.get(iter.getName()) != null) {
                        Object obj = map.get(iter.getName());
                        if (!(obj instanceof List)) {
                            mapList = new ArrayList();
                            mapList.add(obj);
                            mapList.add(iter.getText());
                        }
                        if (obj instanceof List) {
                            mapList = (List) obj;
                            mapList.add(iter.getText());
                        }
                        map.put(iter.getName(), mapList);
                    } else
                        map.put(iter.getName(), iter.getText());
                }
            }
        } else
            map.put(e.getName(), e.getText());
        return map;
    }*/
//    public static String  reSuccess(VoYYT_HEAD head, VoYYT_BODY body , String xmlStr) throws DocumentException {
//        String date = DateUtils.date2Str(new Date(),DateUtils.FORMAT_YYYYMMDDHHMMSS);
//        String xml = "\n" +
//                "\n" +
//                "\n" +
//                ""+head.getN_VER()+"\n" +
//                ""+head.getN_MSGNO()+"\n" +
//                ""+head.getN_SENDID()+"\n" +
//                ""+head.getN_SENDNM()+"\n" +
//                ""+head.getN_RECEID()+"\n" +
//                ""+head.getN_RECENM()+"\n" +
//                ""+head.getN_AKB020()+"\n" +
//                ""+head.getN_YKB211()+"\n" +
//                "\n" +
//                "\n" +
//                ""+body.getN_MSGID()+"\n" +
//                ""+date+"\n" +
//                ""+body.getN_REFMSGID()+"\n" +
//                "\n" +
//                "\n" +
//                "\n" +
//                "\n" +
//                "\n" +
//                "\n" +xmlStr+
//                "\n" +
//                "\n" +
//                "\n" +
//                "0000\n" +
//                "\n" +
//                "\n" +
//                "";
//        //文档中写需要替换,如不需要可以注释
////        xml.replaceAll("<","<");
////        xml.replaceAll(">",">");
//        return xml;
//    }

    // 截取xml内容的函数 by chenhao
    public static String regexLabel(String xml,String label) {
        String context = "";
        //正则表达式
        String regex = "<"+label+">(.*?)";
        Pattern pattern = Pattern.compile(regex);
        Matcher m = pattern.matcher(xml);
        List list = new ArrayList();
        while(m.find()){
            int i = 1;
            list.add(m.group(i));
            i++;
        }
        if(list.size() > 0){
            context = list.get(0);
        }
        return context;
    }

//    public static String  reFalil(VoYYT_HEAD head,  VoYYT_BODY body ,String fail) throws DocumentException {
//        String date = DateUtils.date2Str(new Date(),DateUtils.FORMAT_YYYYMMDDHHMMSS);
//        String xml = "\n" +
//                "\n" +
//                "\n" +
//                ""+head.getN_VER()+"\n" +
//                ""+head.getN_MSGNO()+"\n" +
//                ""+head.getN_SENDID()+"\n" +//医院编码
//                ""+head.getN_SENDNM()+"\n" +//医院名称
//                ""+head.getN_RECEID()+"\n" +//接收方编码
//                ""+head.getN_RECENM()+"\n" +//接收方名称
//                ""+head.getN_AKB020()+"\n" +//医院编码
//                ""+head.getN_YKB211()+"\n" +//社区编码
//                "\n" +
//                "\n" +
//                ""+body.getN_MSGID()+"\n" +//发送方报文ID
//                "\n" +
//                "\n" +
//                "\n" +
//                ""+date+"\n" +
//                "0001960000000001\n" +//接收方报文ID
//                "\n" +
//                "\n" +
//                "\n" +
//                "\n" +
//                "" +
//                "\n" +
//                "-1\n" +
//                ""+fail+"\n" +
//                "\n" +
//                "";
//        //文档中写需要替换,如不需要可以注释
//        xml.replaceAll("<","<");
//        xml.replaceAll(">",">");
//        return xml;
//    }

    public static void main(String[] args) throws DocumentException {
        String xml = "\n" +
                "\n" +
                "  \n" +
                "    1.0\n" +
                "    1201\n" +
                "    \n" +
                "    000139\n" +
                "    000139\n" +
                "    服务平台\n" +
                "    \n" +
                "    100000\n" +
                "  \n" +
                "  \n" +
                "    \n" +
                "    \n" +
                "    \n" +
                "    1000001018068539\n" +
                "    \n" +
                "    \n" +
                "      \n" +
                "        \n" +
                "          \n" +
                "            1\n" +
                "            1\n" +
                "          \n" +
                "        \n" +
                "      \n" +
                "    \n" +
                "    \n" +
                "      \n" +
                "        \n" +
                "          \n" +
                "        \n" +
                "      \n" +
                "    \n" +
                "  \n" +
                "";
        VoJytBaseDTO jybReq = XmlUtils.parseFromXml(VoJytBaseDTO.class, xml);
        System.out.println(JSON.toJSONString(jybReq));

        xml = "\n" +
                "  \n" +
                "    1.0\n" +
                "    1201\n" +
                "    000139\n" +
                "    天津市红桥医院\n" +
                "    100000\n" +
                "    津医通平台\n" +
                "    000193\n" +
                "    \n" +
                "  \n" +
                "  \n" +
                "    00013920211130184928\n" +
                "    \n" +
                "      \n" +
                "    \n" +
                "    20211130064928\n" +
                "    \n" +
                "    \n" +
                "      \n" +
                "    \n" +
                "    0000\n" +
                "    成功\n" +
                "  \n" +
                "";
        Document document = DocumentHelper.parseText(xml);
        System.out.println("=================>"+document.asXML());
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy