使用场景
当下虽然json的数据格式盛行,但是xml依然有他的用武之地
比如微信支付的回调报文
就是以下这种格式
工具类代码.java
import com.thoughtworks.xstream.XStream;
/**
* data 2017-07-07
* @author lijinquan
*/
public class XMLUtilly {
/**
*func 对象转xml
* data 2017-07-07
* @author lijinquan
*
**/
public static String toXML(Object request) {
XStream xstreamReq = new XStream(new XppDriver());
xstreamReq.alias("xml", request.getClass());
String requestXML = xstreamReq.toXML(request).replace("\n", "").replace("__", "_");
return requestXML;
}
/**
*func
* data 2017-07-07
* @author lijinquan
* param :resultClass 指定要转换成的类型
* param :responseXML xml字符串
**/
public static Object fromXML2WechatResult(Class resultClass, String responseXML,
String root) {
XStream xstreamRes = new XStream(new XppDriver() {
public HierarchicalStreamWriter createWriter(Writer out) {
return new PrettyPrintWriter(out) {
boolean cdata = true;
@SuppressWarnings("rawtypes")
public void startNode(String name, Class clazz) {
super.startNode(name, clazz);
}
protected void writeText(QuickWriter writer, String text) {
if (cdata) {
writer.write("<![CDATA[");
writer.write(text);
writer.write("]]>");
} else {
writer.write(text);
}
}
};
}
});
xstreamRes.alias(root, resultClass);
Object response = xstreamRes.fromXML(responseXML);
return response;
}
/**
*func xml字符串转成map
* data 2017-07-07
* @author lijinquan
* param :strXml字符串
**/
public static Map<String, String> xmlToMap(String strXml) throws Exception {
Map<String, String> data = new HashMap<String, String>();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
InputStream stream = new ByteArrayInputStream(strXml.getBytes("UTF-8"));
org.w3c.dom.Document doc = documentBuilder.parse(stream);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getDocumentElement().getChildNodes();
for (int idx = 0; idx < nodeList.getLength(); ++idx) {
Node node = nodeList.item(idx);
if (node.getNodeType() == Node.ELEMENT_NODE) {
org.w3c.dom.Element element = (org.w3c.dom.Element) node;
data.put(element.getNodeName(), element.getTextContent());
}
}
try {
stream.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return data;
}
/**
*func map字符串转成xml
* data 2017-07-07
* @author lijinquan
* param :strXml字符串
**/
public static String mapToXml(Map<String, String> data) throws Exception {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
org.w3c.dom.Document document = documentBuilder.newDocument();
org.w3c.dom.Element root = document.createElement("xml");
document.appendChild(root);
for (String key : data.keySet()) {
String value = data.get(key);
if (value == null) {
value = "";
}
value = value.trim();
org.w3c.dom.Element filed = document.createElement(key);
filed.appendChild(document.createTextNode(value));
root.appendChild(filed);
}
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", "");
try {
writer.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return output;
}
}
测试代码
public static void main(String[] args) {
String postContent="<xml><appKey><![CDATA[e132e42c5f7ce86c30552594907]]></appKey>\n" +
"<appid><![CDATA[wxa5784a9179cb21b2]]></appid>\n" +
"<attach><![CDATA[SADA V-196 map转xml/xml转map]]></attach>\n" +
"<bank_type><![CDATA[OTHERS]]></bank_type>\n" +
"<cash_fee><![CDATA[1]]></cash_fee>\n" +
"<fee_type><![CDATA[CNY]]></fee_type>\n" +
"<is_subscribe><![CDATA[N]]></is_subscribe>\n" +
"<mch_id><![CDATA[1608412914]]></mch_id>\n" +
"<nonce_str><![CDATA[gA63kz32nty2DSu5CFEQSwx8V6ulirgq]]></nonce_str>\n" +
"<openid><![CDATA[oLPst4xXiA9m-MVGJBcacj1190ww]]></openid>\n" +
"<out_trade_no><![CDATA[BO7721042233469]]></out_trade_no>\n" +
"<result_code><![CDATA[SUCCESS]]></result_code>\n" +
"<return_code><![CDATA[SUCCESS]]></return_code>\n" +
"<sign><![CDATA[AD33353EBC82C501CB4FA3A05008BCCC]]></sign>\n" +
"<time_end><![CDATA[20210422174036]]></time_end>\n" +
"<total_fee>1</total_fee>\n" +
"<trade_type><![CDATA[JSAPI]]></trade_type>\n" +
"<transaction_id><![CDATA[4200001039202104226938577739]]></transaction_id>\n" +
"</xml>";
Map<String, String> map = null;
try {
map = WxUtils.xmlToMap(postContent);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(map);
}
结果展示
更多功效请自行尝试,如有错漏,请评论指正