1、解析xml文件工具类
package cn.xd.dcol.railway.business.utils;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.dom4j.*;
import org.dom4j.io.SAXReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
public class TimsXmlJsonUtil {
public static String xmlToString11(String xmlFileName){
SAXReader saxReader=new SAXReader();
Document document;
String xmlString="";
try {
document = saxReader.read(new File(xmlFileName));
xmlString=document.asXML();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
xmlString="";
}
//String xmlString=document.asXML();
return xmlString;
}
}
2、String转json格式方法
// xml转json
public static JSONObject xml2Json(String xmlStr) throws IOException, DocumentException {
if (StringUtils.isEmpty(xmlStr)) {
return null;
}
// xmlStr = xmlStr.replaceAll("\\\n", "");
// log.info("将换行转为空格:"+xmlStr);
JSONObject json = new JSONObject();
Map<String, Object> map = new LinkedHashMap<>();
InputStream is = new ByteArrayInputStream(xmlStr.getBytes("UTF-8"));
SAXReader reader = new SAXReader();
Document doc = reader.read(is);
Element element = doc.getRootElement();
// log.info("doc元素:"+doc.getStringValue());
dom4j2Json(element, json);
// log.info("map:"+map);
if (json.toJSONString().contains("DATASET")) {
json = json.getJSONObject("DATASET");
}
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 (ObjectUtil.isNotEmpty(attr.getValue())) {
json.put(attr.getName(), attr.getValue());
}
}
Iterator<Element> chdEl = element.elementIterator();
if (!chdEl.hasNext() && !StringUtils.isEmpty(element.getText())) {// 如果没有子元素,只有一个值
json.put(element.getName(), element.getText());
}
while (chdEl.hasNext()) {
Element e = chdEl.next();
// log.info(e);
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.isEmpty(attr.getValue())) {
json.put(attr.getName(), attr.getValue());
}
}
if (!e.getText().isEmpty()) {
json.put(e.getName(), e.getText());
} else {
json.put(e.getName(), "");
}
}
}
}