xml解析工具类:
package com.nio.dms.invoices.utils;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.dms.function.utils.common.StringUtils;
/**
* xml数据格式转换成json格式
* @author lulu.wang.o
* @date 2019年6月8日
*/
public class XmlToJsonUtils {
public static String xmlToJsonUtils(String xmlData) {
JSONObject json = new JSONObject();
Document doc;
try {
doc = DocumentHelper.parseText(xmlData);
dom4j2Json(doc.getRootElement(), json);
System.out.println("xml2Json:" + json.toJSONString());
} catch (DocumentException e) {
e.printStackTrace();
}
return json.toJSONString();
}
/**
* xml转json
* @param element
* @param json
*/
public static void dom4j2Json(Element element, JSONObject json) {
for (Object o : element.attributes()) {
Attribute attr = (Attribute) o;
if (!StringUtils.isNullOrEmpty(attr.getValue())) {
json.put("@" + attr.getName(), attr.getValue());
}
}
List<Element> chdEl = element.elements();
if (chdEl.isEmpty() && !StringUtils.isNullOrEmpty(element.getText())) {// 如果没有子元素,只有一个值
json.put(element.getName(), element.getText());
}
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 (!StringUtils.isNullOrEmpty(attr.getValue())) {
json.put("@" + attr.getName(), attr.getValue());
}
}
if (!e.getText().isEmpty()) {
json.put(e.getName(), e.getText());
}
}
}
}
}
Controller控制层部分代码:
@SuppressWarnings("unchecked")
@RequestMapping(value ="/addRenewVehicle",method = RequestMethod.POST,consumes ="application/xml")
@ResponseBody
public BaseResult addRenewVehicle(@RequestBody String data){
logger.info("一键续包接口调用路径:/nservice/addRenewVehicle,request data:"+data);
try {
//xml数据格式转化成json
String jsonData = XmlToJsonUtils.xmlToJsonUtils(data);
logger.info("一键续包接口请求数据json格式:"+jsonData);
JSONObject fromObject = JSONObject.fromObject(jsonData);