Xstream(对象和xml转换)
package com.vcredit.framework.utils;
import java.io.Writer;
import org.apache.commons.lang3.StringUtils;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;
import com.thoughtworks.xstream.io.xml.XppDriver;
/**
* XML工具类
*/
public class XmlUtils {
/**
* 创建XStream
*/
private static XStream createXstream() {
XStream xstream = new XStream(new MyXppDriver(false));
xstream.autodetectAnnotations(true);
return xstream;
}
/**
* 支持注解转化XML
*/
public static String toXML(Object obj, Class<?> cls) {
if (obj == null) {
return null;
}
XStream xstream = createXstream();
xstream.processAnnotations(cls);
return getDefaultXMLHeader() + xstream.toXML(obj);
}
/**
* Object 转化 XML
*/
public static String toXML(Object obj) {
if (obj == null) {
return null;
}
XStream xstream = createXstream();
return getDefaultXMLHeader() + xstream.toXML(obj);
}
/**
* XML转化为JAVA对象
*/
@SuppressWarnings("unchecked")
public static <T> T xml2Obj(String xml, Class<?> cls) {
if (StringUtils.isBlank(xml)) {
return null;
}
XStream xstream = createXstream();
if (cls != null) {
xstream.processAnnotations(cls);
}
return (T) xstream.fromXML(xml);
}
/**
* XML转化为JAVA对象
*/
public static <T> T xml2Obj(String xml) {
return xml2Obj(xml, null);
}
private static String getDefaultXMLHeader() {
return "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
}
/**
*
* @description XppDriver
*
* @author lixining
* @version $Id: XmlUtils.java, v 0.1 2015年8月18日 上午9:46:57 lixining Exp $
*/
public static class MyXppDriver extends XppDriver {
boolean useCDATA = false;
MyXppDriver(boolean useCDATA) {
super(new XmlFriendlyNameCoder("__", "_"));
this.useCDATA = useCDATA;
}
@Override
public HierarchicalStreamWriter createWriter(Writer out) {
if (!useCDATA) {
return super.createWriter(out);
}
return new PrettyPrintWriter(out) {
boolean cdata = true;
@Override
public void startNode(String name, @SuppressWarnings("rawtypes") Class clazz) {
super.startNode(name, clazz);
}
@Override
protected void writeText(QuickWriter writer, String text) {
if (cdata) {
writer.write(cDATA(text));
} else {
writer.write(text);
}
}
private String cDATA(String text) {
return "<![CDATA[" + text + "]]>";
}
};
}
}
}
调用方法String xmlForMobileScore = XmlUtils.toXML(decisionReqForMobileScore);
再写到文件中:
String decisionReqName = getSaveFile(timestamp, modelName, "req");
String decisionResName = getSaveFile(timestamp, modelName, "res");
logger.info("DecisionClient->Request->" + timestamp + "->" + xml);
FileUtils.write(new File(decisionReqName), xml, "utf-8");
解析xml:dom4j
private DecisionResponse parseDecisionRespXML(String resultXml) throws BusinessException {
if (StringUtils.isBlank(resultXml)) {
throw new BusinessException("决策无数据返回");
}
DecisionResponse result = new DecisionResponse();
Element root = Dom4jUtils.getRoot(resultXml);
Element decisionResult = root.element("DecisionResult");
// 决策结果-建议拒绝 or 通过
Element resultElement = decisionResult.element("Result");
result.setResult(resultElement.getStringValue());
// 解析拒绝原因
if (!StringUtils.equals(result.getResult(), "通过")) {
Element ruleSetElement = decisionResult.element("RuleResultSets");
List<String> modList = parseRejectRules(decisionResult.element("RejectReasonList"));
parseRuleSet(result, ruleSetElement, modList);
}
// 解析决策评分卡结果
Element vbInfoSetElement = decisionResult.element("VBInfo");
parseVBInfoSet(result,vbInfoSetElement);
// 解析决策评分细节
Element ruleResultElement = decisionResult.element("RuleResultCanShowSets");
parseruleResult(result,ruleResultElement);
Element ruleResultCanShowSets = decisionResult.element("RuleResultCanShowSets");
parseRelatedRate(result, ruleResultCanShowSets);
logger.info("Decision Result -> " + GsonUtils.toJson(result));
return result;
}
package com.vcredit.framework.utils;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Dom4jUtils {
private static final Logger logger = LoggerFactory.getLogger(Dom4jUtils.class);
public static Document getDocument(String xml) {
Document document = null;
try {
document = DocumentHelper.parseText(xml);
if (document == null) {
throw new RuntimeException("document is null");
}
return document;
} catch (Exception e) {
logger.error("parse xml fail", e);
throw new RuntimeException("get document fail", e);
}
}
/**
* 解析XML获取Root节点
*
* @param xml
* @return Element
*/
public static Element getRoot(String xml) {
Document document = getDocument(xml);
return document.getRootElement();
}
/**
* 获取节点值
*
* @param root
* @param nodeName
* @return String
*/
public static String getValue(Element root, String nodeName) {
try {
if (root == null || StringUtils.isBlank(nodeName)) {
return null;
}
Element nodeElement = root.element(nodeName);
if (nodeElement == null) {
return null;
}
return nodeElement.getTextTrim();
} catch (Exception e) {
logger.error("get node(" + nodeName + ") value fail");
return null;
}
}
// public static void main(String[] args) throws IOException {
// Document doc = getDocument(FileUtils.readFileToString(new File("e:\\test\\result.xml"), "utf-8"));
// Element root = doc.getRootElement();
// List<Element> elementList = root.elements();
// for (Element element : elementList) {
// System.err.println("-------------------------->" + element.getName());
// System.err.println(element.getStringValue());
// }
// System.err.println("test");
// }
}