移除JDom重写xml工具

This commit is contained in:
egan
2018-04-28 18:47:18 +08:00
parent 8a2a90a331
commit bae9f4f671
2 changed files with 181 additions and 116 deletions

View File

@@ -1,53 +1,42 @@
package com.egzosn.pay.common.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.egzosn.pay.common.bean.result.PayException;
import com.egzosn.pay.common.exception.PayErrorException;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.io.StringWriter;
import java.util.Map;
/**
* XML工具
* @author egan
* <pre>
* email egzosn@gmail.com
* date 2016-6-2 19:45:06
* </pre>
*
* @author egan
* <pre>
* email egzosn@gmail.com
* date 2016-6-2 19:45:06
* </pre>
*/
public class XML {
/**
* 解析xml并转化为Json值
* @param content json字符串
* @return Json值
*/
public static JSONObject toJSONObject(String content){
if (null == content || "".equals(content)) {
return null;
}
try (InputStream in = new ByteArrayInputStream(content.getBytes("UTF-8"))){
return (JSONObject) inputStream2Map(in, null);
} catch (IOException e) {
throw new PayErrorException(new PayException("IOException", e.getMessage()));
}
}
/**
* 解析xml并转化为json值
*
* @param in 输入流
* @return Json值
*/
@@ -58,7 +47,7 @@ public class XML {
}
try {
return (JSONObject)inputStream2Map(in, null);
return (JSONObject) inputStream2Map(in, null);
} catch (IOException e) {
throw new PayErrorException(new PayException("IOException", e.getMessage()));
}
@@ -67,40 +56,42 @@ public class XML {
}
/**
* 解析xml并转化为Json值
*
* @param in xml输入流
* @param m 参数集
* @return 整理完成的参数集
* @throws IOException xml io转化异常
* @param content json字符串
* @return Json值
*/
public static Map inputStream2Map(InputStream in, Map m) throws IOException {
if (null == m){
m = new JSONObject();
public static JSONObject toJSONObject(String content) {
if (null == content || "".equals(content)) {
return null;
}
SAXBuilder builder = new SAXBuilder();
try {
Document doc = builder.build(in);
Element root = doc.getRootElement();
List list = root.getChildren();
Iterator it = list.iterator();
while (it.hasNext()) {
Element e = (Element) it.next();
String k = e.getName();
Object v = "";
List children = e.getChildren();
if (children.isEmpty()) {
v = e.getTextNormalize();
} else {
v = getChildren(children);
}
m.put(k, v);
}
} catch (JDOMException e) {
throw new PayErrorException(new PayException("JDOMException", e.getMessage()));
try (InputStream in = new ByteArrayInputStream(content.getBytes("UTF-8"))) {
return (JSONObject) inputStream2Map(in, null);
} catch (IOException e) {
throw new PayErrorException(new PayException("IOException", e.getMessage()));
}
return m;
}
/**
* 解析xml并转化为Json值
*
* @param content json字符串
* @return Json值
*/
public static <T> T toBean(String content, Class<T> clazz) {
if (null == content || "".equals(content)) {
return null;
}
try (InputStream in = new ByteArrayInputStream(content.getBytes("UTF-8"))) {
return inputStream2Bean(in, clazz);
} catch (IOException e) {
throw new PayErrorException(new PayException("IOException", e.getMessage()));
}
}
/**
@@ -109,46 +100,35 @@ public class XML {
* @param children 集合
* @return String 子结点的xml
*/
public static String getChildrenText(List children) {
StringBuffer sb = new StringBuffer();
if (!children.isEmpty()) {
Iterator it = children.iterator();
while (it.hasNext()) {
Element e = (Element) it.next();
String name = e.getName();
String value = e.getTextNormalize();
List list = e.getChildren();
sb.append("<" + name + ">");
if (!list.isEmpty()) {
sb.append(getChildrenText(list));
public static JSON getChildren(NodeList children) {
JSON json = null;
for (int idx = 0; idx < children.getLength(); ++idx) {
Node node = children.item(idx);
NodeList nodeList = node.getChildNodes();
if (node.getNodeType() == Node.ELEMENT_NODE && nodeList.getLength() <= 1) {
if (null == json) {
json = new JSONObject();
}
((JSONObject) json).put(node.getNodeName(), node.getTextContent());
} else if (node.getNodeType() == Node.ELEMENT_NODE && nodeList.getLength() > 1) {
if (null == json) {
json = new JSONObject();
}
if (json instanceof JSONObject) {
JSONObject j = ((JSONObject) json);
if (j.containsKey(node.getNodeName())) {
JSONArray array = new JSONArray();
array.add(json);
json = array;
} else {
j.put(node.getNodeName(), getChildren(nodeList));
}
}
sb.append(value);
sb.append("</" + name + ">");
}
}
return sb.toString();
}
/**
* 获取子结点的xml
*
* @param children 集合
* @return String 子结点的xml
*/
public static Object getChildren(List children) {
JSONObject json = new JSONObject();
if (!children.isEmpty()) {
Iterator it = children.iterator();
while (it.hasNext()) {
Element e = (Element) it.next();
String name = e.getName();
String value = e.getTextNormalize();
List list = e.getChildren();
if (!list.isEmpty()) {
json.put(name, getChildren(list));
}else {
json.put(name, value);
if (json instanceof JSONArray) {
JSONObject c = new JSONObject();
c.put(node.getNodeName(), getChildren(nodeList));
((JSONArray) json).add(c);
}
}
}
@@ -156,25 +136,113 @@ public class XML {
return json;
}
/**
* 将请求参数转换为xml格式的string
* @param parameters 请求参数
* @return xml
/***
* xml 解析成对应的对象
* @param in 输入流
* @param clazz 需要转化的类
* @param <T> 类型
* @return 对应的对象
* @throws IOException xml io转化异常
*/
public static String getMap2Xml(Map<String, Object> parameters) {
StringBuffer sb = new StringBuffer();
sb.append("<xml>");
for (String key : parameters.keySet()){
if ("attach".equalsIgnoreCase(key) || "body".equalsIgnoreCase(key) || "attach".equalsIgnoreCase(key) || "sign".equalsIgnoreCase(key)) {
sb.append("<" + key + ">" + "<![CDATA[" + parameters.get(key) + "]]></" + key + ">");
} else {
sb.append("<" + key + ">" + parameters.get(key) + "</" + key + ">");
}
public static <T> T inputStream2Bean(InputStream in, Class<T> clazz) throws IOException {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
org.w3c.dom.Document doc = documentBuilder.parse(in);
doc.getDocumentElement().normalize();
NodeList children = doc.getDocumentElement().getChildNodes();
JSON json = getChildren(children);
return json.toJavaObject(clazz);
} catch (Exception e) {
// e.printStackTrace();
throw new PayErrorException(new PayException("XML failure", "XML解析失败\n" + e.getMessage()));
} finally {
in.close();
}
sb.append("</xml>");
return sb.toString();
}
/**
* @param in xml输入流
* @param m 参数集
* @return 整理完成的参数集
* @throws IOException xml io转化异常
*/
public static Map inputStream2Map(InputStream in, Map m) throws IOException {
if (null == m) {
m = new JSONObject();
}
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
org.w3c.dom.Document doc = documentBuilder.parse(in);
doc.getDocumentElement().normalize();
NodeList children = doc.getDocumentElement().getChildNodes();
for (int idx = 0; idx < children.getLength(); ++idx) {
Node node = children.item(idx);
NodeList nodeList = node.getChildNodes();
if (node.getNodeType() == Node.ELEMENT_NODE && nodeList.getLength() <= 1) {
m.put(node.getNodeName(), node.getTextContent());
} else if (node.getNodeType() == Node.ELEMENT_NODE && nodeList.getLength() > 1) {
m.put(node.getNodeName(), getChildren(nodeList));
}
}
} catch (Exception e) {
// e.printStackTrace();
throw new PayErrorException(new PayException("XML failure", "XML解析失败\n" + e.getMessage()));
} finally {
in.close();
}
return m;
}
/**
* 将Map转换为XML格式的字符串
*
* @param data Map类型数据
* @return XML格式的字符串
*/
public static String getMap2Xml(Map<String, Object> data) {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = null;
try {
documentBuilder = documentBuilderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
org.w3c.dom.Document document = documentBuilder.newDocument();
org.w3c.dom.Element root = document.createElement("xml");
document.appendChild(root);
for (String key : data.keySet()) {
Object value = data.get(key);
if (value == null) {
value = "";
}
value = value.toString().trim();
org.w3c.dom.Element filed = document.createElement(key);
filed.appendChild(document.createTextNode(value.toString()));
root.appendChild(filed);
}
try {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(document);
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
return output;
} catch (TransformerException e) {
e.printStackTrace();
}
return "";
}
}