[/login]

package org.hyjk.czzf.until;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

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

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


public class HisXml {  
  

    /**
     * xml转json
     * @param xmlStr
     * @return
     * @throws DocumentException
     */
    public static JSONObject xml2Json(String xmlStr)  {
        Document doc;
        try {
            doc = DocumentHelper.parseText(xmlStr);
              JSONObject json=new JSONObject();
                dom4j2Json(doc.getRootElement(), json);
                return json;
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        JSONObject json=new JSONObject();
        return json;
    }

    /**
     * xml转json
     * @param element
     * @param json
     */
    public 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> chdEl=element.elements();
        if(chdEl.isEmpty()&&!isEmpty(element.getText())){//如果没有子元素,只有一个值
            json.put(element.getName(), element.getText());
            if(element.getText()==null || element.getText().equals("")) {
                json.put(element.getName(), "");
            }
        }

        for(Element e:chdEl){//有子元素
            if(!e.elements().isEmpty()){//子元素也有子元素
                JSONObject chdjson=new JSONObject();
                dom4j2Json(e,chdjson);
                Object o=json.get(e.getName());
                if(o!=null){
                    JSONArray jsona=null;
                    if(o instanceof JSONObject){//如果此元素已存在,则转为jsonArray
                        JSONObject jsono=(JSONObject)o;
                        json.remove(e.getName());
                        jsona=new JSONArray();
                        jsona.add(jsono);
                        jsona.add(chdjson);
                    }
                    if(o instanceof JSONArray){
                        jsona=(JSONArray)o;
                        jsona.add(chdjson);
                    }
                    json.put(e.getName(), jsona);
                }else{
                    if(!chdjson.isEmpty()){
                        json.put(e.getName(), chdjson);
                    }
                }
            }else{//子元素没有子元素
                for(Object o:element.attributes()){
                    Attribute attr=(Attribute)o;
                    if(!isEmpty(attr.getValue())){
                        json.put("@"+attr.getName(), attr.getValue());
                    }
                }
                if(!e.getText().isEmpty()){
                    json.put(e.getName(), e.getText());
                }else {
                    json.put(e.getName(), "");
                }
            }
        }
    }

    public static boolean isEmpty(String str) {

        if (str == null || str.trim().isEmpty() || "null".equals(str)) {
            return true;
        }
        return false;
    }

    /**
     * Json to xml string.
     *
     * @param json the json
     * @return the string
     */
    public static String json2Xml(String json){
        try {
            StringBuffer buffer = new StringBuffer();
            buffer.append("<xml>");
            //buffer.append("<?xml version=\"1.0\" encoding=\"utf-8\"?><xml>");
            JSONObject jObj = JSON.parseObject(json);
            jsonToXmlstr(jObj,buffer);
            buffer.append("</xml>");
            return buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
 
 
    /**
     * Json to xmlstr string.
     *
     * @param jObj   the j obj
     * @param buffer the buffer
     * @return the string
     */
    public static String jsonToXmlstr(JSONObject jObj,StringBuffer buffer ){
        Set<Map.Entry<String, Object>> se = jObj.entrySet();
        for(Iterator<Map.Entry<String, Object>> it = se.iterator(); it.hasNext(); )
        {
            Map.Entry<String, Object> en = it.next();
            if(en.getValue().getClass().getName().equals("com.alibaba.fastjson.JSONObject")){
                buffer.append("<"+en.getKey()+">");
                JSONObject jo = jObj.getJSONObject(en.getKey());
                jsonToXmlstr(jo,buffer);
                buffer.append("</"+en.getKey()+">");
            }else if(en.getValue().getClass().getName().equals("com.alibaba.fastjson.JSONArray")){
                JSONArray jarray = jObj.getJSONArray(en.getKey());
                for (int i = 0; i < jarray.size(); i++) {
                    buffer.append("<"+en.getKey()+">");
                    JSONObject jsonobject =  jarray.getJSONObject(i);
                    jsonToXmlstr(jsonobject,buffer);
                    buffer.append("</"+en.getKey()+">");
                }
            }else if(en.getValue().getClass().getName().equals("java.lang.String")){
                buffer.append("<"+en.getKey()+">"+en.getValue());
                buffer.append("</"+en.getKey()+">");
            }
        }
        return buffer.toString();
    }
 
    /**
     * The entry point of application.
     *
     * @param args the input arguments
     */
    public static void main(String[] args) {
        System.out.println(json2Xml("{\"result\":\"0\",\"reason\":\"成功\",\"list\":[{\"totalElements\":13,\"totalPages\":1,\"first\":true,\"last\":true,\"content\":[{\"编码\":\"1\",\"名称\":\"普通号\",\"是否专家\":\"0\",\"rankno\":1},{\"编码\":\"2,3\",\"名称\":\"专家号\",\"是否专家\":\"1\",\"rankno\":2},{\"编码\":\"4\",\"名称\":\"知名专家\",\"是否专家\":\"1\",\"rankno\":4},{\"编码\":\"7\",\"名称\":\"普通号(专病)\",\"是否专家\":\"1\",\"rankno\":7},{\"编码\":\"8\",\"名称\":\"普通号(简易)\",\"是否专家\":\"0\",\"rankno\":8},{\"编码\":\"9\",\"名称\":\"中医主任医师\",\"是否专家\":\"1\",\"rankno\":9},{\"编码\":\"10\",\"名称\":\"中医副主任医师\",\"是否专家\":\"1\",\"rankno\":10},{\"编码\":\"11\",\"名称\":\"中医普通医师\",\"是否专家\":\"0\",\"rankno\":11},{\"编码\":\"12\",\"名称\":\"中医普通医师(专病)\",\"是否专家\":\"1\",\"rankno\":12},{\"编码\":\"13\",\"名称\":\"京津主任专家门诊\",\"是否专家\":\"1\",\"rankno\":13},{\"编码\":\"14\",\"名称\":\"京津副主任专家门诊\",\"是否专家\":\"1\",\"rankno\":14},{\"编码\":\"15\",\"名称\":\"京津专家门诊(复诊)\",\"是否专家\":\"1\",\"rankno\":15},{\"编码\":\"16\",\"名称\":\"慢性病门诊\",\"是否专家\":\"0\",\"rankno\":16}]}]}"));
        System.out.println(xml2Json("<xml><resultCode>1</resultCode><resultDesc>成功</resultDesc><resultObjects></resultObjects></xml>"));
    }
}

[/login]

最后修改:2022 年 03 月 30 日
如果觉得我的文章对你有用,请随意赞赏