package com.yihu.wlyy.util;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.dom4j.tree.DefaultAttribute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.*;
public class XMLUtil {
private static Logger logger = LoggerFactory.getLogger(XMLUtil.class);
/**
* 把xml字符串转换成 Document对象。
*
* @param xml 需要转换的xml字符串
* @return 返回Document对象
* @throws Exception 如果转换成Document对象异常的话抛出异常。
*/
public static Document parseXml(String xml) throws Exception {
try {
return DocumentHelper.parseText(xml);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new Exception("传入的 xml 不是标准的xml字符串,请检查字符串是否合法。");
}
}
/**
* 转换成xml字符串
*
* @param xmlDoc 需要解析的xml对象
* @throws Exception
*/
public static String toXML_UTF_8(Document xmlDoc) throws Exception {
return toXML(xmlDoc, "UTF-8", true);
}
/**
* 转换成xml字符串
*
* @param xmlDoc 需要解析的xml对象
* @throws Exception
*/
public static String toXML_GBK(Document xmlDoc) throws Exception {
return toXML(xmlDoc, "GBK", true);
}
/**
* 转换成xml字符串
*
* @param xmlDoc 需要解析的xml对象
* @param encoding 编码格式:UTF-8、GBK
* @param iscom 是否为紧凑型格式
* @return 修正完成后的xml字符串
* @throws Exception
*/
public static String toXML(Document xmlDoc, String encoding,
boolean iscom) throws Exception {
ByteArrayOutputStream byteRep = new ByteArrayOutputStream();
OutputFormat format = null;
if (iscom) {
format = OutputFormat.createCompactFormat();// 紧凑型格式
} else {
format = OutputFormat.createPrettyPrint();// 缩减型格式
}
format.setEncoding(encoding);// 设置编码
format.setTrimText(false);// 设置text中是否要删除其中多余的空格
XMLWriter xw;
try {
xw = new XMLWriter(byteRep, format);
xw.write(xmlDoc);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new Exception("传入的编码格式错误,请传入正确的编码。");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new Exception("文档转换成xml字符串时出错。" + xmlDoc.asXML());
}
return byteRep.toString();
}
/**
* 对节点Element 添加节点。
*
* @param e 需要添加的节点
* @param name 添加的节点的名称
* @param value 添加的内容
*
* Demo:
* < Root > aaa < /Root >
*
* call--> addChildElement(root, "A", "a");
*
* result--> < Root >< A >a< /A >< /Root >
*/
public static void addElement(Element e, String name, Object value) {
if (isBlank(value)) {
e.addElement(name).addText("");
} else {
e.addElement(name).addText(value.toString());
}
}
/**
* 判断对象是否为空!(null,"", "null")
*
* @param value
* @return
*/
private static boolean isBlank(String value) {
if (value == null || value.length() == 0) {
return true;
} else if (StringUtils.isEmpty(value)) {
return true;
} else {
return false;
}
}
/**
* 判断对象是否非空!(null,"", "null")
*
* @param obj
* @return
*/
public static boolean isNotBlank(Object obj) {
return !isBlank(obj);
}
/**
* 判断对象是否为空!(null,"", "null")
*
* @param obj
* @return
*/
public static boolean isBlank(Object obj) {
if (obj == null) {
return true;
}
if (obj instanceof String) {
return isBlank((String) obj);
} else {
return isBlank(obj.toString());
}
}
public static void addElement(Element e, String name, Integer value) {
Element current = e.addElement(name);
if (value != null) {
current.setText(Integer.toString(value));
}
}
/**
* 添加CDATA 类型节点
*
* @param e
* @param name
* @param value
*/
public static void addCDATAElement(Element e, String name, String value) {
Element current = e.addElement(name);
if (value != null) {
current.addCDATA(value.trim());
}
}
/**
* 添加CDATA 类型节点
*
* @param e
* @param name
* @param value
*/
public static void addCDATAElement(Element e, String name, Integer value) {
Element current = e.addElement(name);
if (value != null) {
current.addCDATA(value.toString());
}
}
/**
* 获取节点中的整数
*
* @throws Exception
*/
public static int getInt(Element e, String name, boolean isMust) throws Exception {
Element current = e.element(name);
if (current == null || current.getText() == null || "".equals(current.getText().trim()) || current.getText().length() <= 0) {
if (isMust) {
throw new Exception("在 $" + e.asXML() + "$中获取节点:" + name + " 的值为空。");
}
return 0;
}
Integer i = 0;
try {
i = Integer.parseInt(current.getTextTrim());
} catch (NumberFormatException e1) {
i = 0;
if (isMust) {
throw new Exception("在 $" + e.asXML() + "$中获取节点:" + name + " 的值不是整形。");
}
}
return i;
}
/**
* 获取节点中的字符串
*
* @throws Exception
*/
public static String getString(Element e, String name, boolean isMust) throws Exception {
return getString(e, name, isMust, null);
}
/**
* 获取节点中的字符串
*
* @param e
* @param name
* @param isMust 是否必填 true 必填 false非必填
* @param defVal 默认值
* @return
* @throws Exception
*/
public static String getString(Element e, String name, boolean isMust, String defVal) throws Exception {
Element current = e.element(name);
if (current == null || current.getText() == null || StringUtils.isEmpty(current.getText().trim())) {
if (isMust) {
throw new Exception("在 $" + e.asXML() + "$中获取节点:" + name + " 的值为空。");
}
return defVal;
}
return current.getTextTrim();
}
public static String ElementStringValue(String str) {
if (str != null) {
return str;
} else {
return "";
}
}
public static Integer ElementIntegerValue(Integer str) {
if (str != null) {
return str;
} else {
return 0;
}
}
public static String ElementValue(String str) {
if (str != null && !str.equalsIgnoreCase("null")) {
return str;
} else {
return "";
}
}
public static String xml2json(String xml){
StringWriter w = new StringWriter();
ObjectMapper objectMapper = new ObjectMapper();
XmlMapper xmlMapper = new XmlMapper();
JsonParser jp;
try {
jp = xmlMapper.getFactory().createParser(xml);
JsonGenerator jg = objectMapper.getFactory().createGenerator(w);
while (jp.nextToken() != null) {
String name = jp.getParsingContext().getCurrentName();
if ("".equals(name)){
jp.overrideCurrentName("text");
}
jg.copyCurrentEvent(jp);
}
jp.close();
jg.close();
} catch (Exception e) {
e.printStackTrace();
}
return w.toString();
}
public static String formatXML(Document doc) throws Exception {
StringWriter out = null;
try {
OutputFormat formate = OutputFormat.createPrettyPrint();
out = new StringWriter();
XMLWriter writer = new XMLWriter(out, formate);
writer.write(doc);
} catch (IOException e) {
e.printStackTrace();
} finally {
out.close();
}
return out.toString();
}
// ---------- map转XML--------------
public static String map2xml(Map dataMap) {
synchronized (XMLUtil.class) {
StringBuilder strBuilder = new StringBuilder();
strBuilder.append("");
strBuilder.append("");
Set objSet = dataMap.keySet();
for (Object key : objSet) {
if (key == null) {
continue;
}
strBuilder.append("<").append(key.toString()).append(">");
Object value = dataMap.get(key);
strBuilder.append(coverter(value));
strBuilder.append("").append(key.toString()).append(">");
}
strBuilder.append("");
return strBuilder.toString();
}
}
public static String coverter(Object[] objects) {
StringBuilder strBuilder = new StringBuilder();
for (Object obj : objects) {
strBuilder.append("- \n");
strBuilder.append(coverter(obj));
strBuilder.append("
\n");
}
return strBuilder.toString();
}
public static String coverter(Collection> objects) {
StringBuilder strBuilder = new StringBuilder();
for (Object obj : objects) {
strBuilder.append("- \n");
strBuilder.append(coverter(obj));
strBuilder.append("
\n");
}
return strBuilder.toString();
}
public static String coverter(Object object) {
if (object instanceof Object[]) {
return coverter((Object[]) object);
}
if (object instanceof Collection) {
return coverter((Collection>) object);
}
StringBuilder strBuilder = new StringBuilder();
if (isObject(object)) {
Class extends Object> clz = object.getClass();
Field[] fields = clz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
if (field == null) {
continue;
}
String fieldName = field.getName();
Object value = null;
try {
value = field.get(object);
} catch (IllegalArgumentException e) {
continue;
} catch (IllegalAccessException e) {
continue;
}
strBuilder.append("<").append(fieldName)
.append(" className=\"").append(
value.getClass().getName()).append("\">");
if (isObject(value)) {
strBuilder.append(coverter(value));
} else if (value == null) {
strBuilder.append("null");
} else {
strBuilder.append(value.toString() + "");
}
strBuilder.append("").append(fieldName).append(">");
}
} else if (object == null) {
strBuilder.append("null");
} else {
strBuilder.append(object.toString());
}
return strBuilder.toString();
}
private static boolean isObject(Object obj) {
if (obj == null) {
return false;
}
if (obj instanceof String) {
return false;
}
if (obj instanceof Integer) {
return false;
}
if (obj instanceof Double) {
return false;
}
if (obj instanceof Float) {
return false;
}
if (obj instanceof Byte) {
return false;
}
if (obj instanceof Long) {
return false;
}
if (obj instanceof Character) {
return false;
}
if (obj instanceof Short) {
return false;
}
if (obj instanceof Boolean) {
return false;
}
return true;
}
// --------------------xml转map---------------
private static void ele2map(Map map, Element ele) {
// 获得当前节点的子节点
List elements = ele.elements();
if (elements.size() == 0) {
// 没有子节点说明当前节点是叶子节点,直接取值即可
map.put(ele.getName(), ele.getText());
} else if (elements.size() == 1) {
// 只有一个子节点说明不用考虑list的情况,直接继续递归即可
Map tempMap = new HashMap();
ele2map(tempMap, elements.get(0));
//设置标签属性
setAttributes(tempMap,elements.get(0));
if (tempMap.size()==1){
map.put(ele.getName(), ele.getText());
}else {
map.put(ele.getName(), tempMap);
}
} else {
// 多个子节点的话就得考虑list的情况了,比如多个子节点有节点名称相同的
// 构造一个map用来去重
Map tempMap = new HashMap();
for (Element element : elements) {
tempMap.put(element.getName(), null);
}
Set keySet = tempMap.keySet();
for (String string : keySet) {
Namespace namespace = elements.get(0).getNamespace();
List elements2 = ele.elements(new QName(string, namespace));
// 如果同名的数目大于1则表示要构建list
if (elements2.size() > 1) {
List