package com.qtzl.alterSales.manager.tools;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.*;
import java.util.Map.Entry;
public class JsonToXmlUtil {
/**
* xml转json字符串 注意:路径和字符串二传一另外一个传null
* 方 法 名:xmlToJson
* @param xmlPath xml路径(和字符串二传一,两样都传优先使用路径)
* @param xmlStr xml字符串(和路径二传一,两样都传优先使用路径)
* @return String
* @throws IOException
* @throws JDOMException
*/
@SuppressWarnings("unchecked")
public static String xmlToJson(String xmlPath,String xmlStr){
SAXBuilder sbder = new SAXBuilder();
Map map = new HashMap();
Document document;
try {
if(xmlPath!=null){
//路径
document = sbder.build(new File(xmlPath));
}else if(xmlStr!=null){
//xml字符
StringReader reader = new StringReader(xmlStr);
InputSource ins = new InputSource(reader);
document = sbder.build(ins);
}else{
return "{}";
}
//获取根节点
Element el = document.getRootElement();
List eList = el.getChildren();
Map rootMap = new HashMap();
//得到递归组装的map
rootMap = xmlToMap(eList,rootMap);
map.put(el.getName(), rootMap);
//将map转换为json 返回
return JSON.toJSONString(map);
} catch (Exception e) {
return "{}";
}
}
/**
* json转xml
* 方 法 名:jsonToXml
* @param json
* @return String
*/
public static String jsonToXml(String json){
try {
StringBuffer buffer = new StringBuffer();
buffer.append("");
buffer.append("");
JSONObject jObj = JSON.parseObject(json);
jsonToXmlstr(jObj,buffer);
buffer.append("");
return buffer.toString();
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* json转str
* 方 法 名:jsonToXmlstr
* @param jObj
* @param buffer
* @return String
*/
public static String jsonToXmlstr(JSONObject jObj,StringBuffer buffer ){
Set> se = jObj.entrySet();
for( Iterator> it = se.iterator(); it.hasNext(); )
{
Entry en = it.next();
if(en.getValue() != null && 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() != null && en.getValue().getClass().getName().equals("com.alibaba.fastjson.JSONArray")){
if (en.getKey().equals("extproperties")) {
JSONArray ja = jObj.getJSONArray(en.getKey());
Iterator