java处理xml和Map互转,xml转换为自定义对象

本文展示了XML在微信支付回调消息中的使用,提供了一套XML与Java对象互相转换的工具类,包括对象转XML和XML转对象的方法,以及XML字符串转Map和Map转XML的功能。测试代码演示了如何将微信支付回调的XML字符串转换为Map。
摘要由CSDN通过智能技术生成

使用场景

当下虽然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);

    }

结果展示

更多功效请自行尝试,如有错漏,请评论指正

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值