package com.slodon.b2b2c.core.util;

import com.slodon.b2b2c.core.response.WxPayCallbackVO;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;

/**
 *
 * @description: xml工具类
 * @author: wuxy
 **/
public class XmlUtils {

    /**
     * 将xml解析成对象
     *
     * @param xml xml
     * @param clazz clazz
     * @param <T> t
     * @return return
     */
    public static <T> T convertToObject(String xml, Class<T> clazz) {
        T _clazz = null;
        StringReader reader = null;
        try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            reader = new StringReader(xml);
            _clazz = (T) unmarshaller.unmarshal(reader);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
        return _clazz;
    }

    public static void main(String[] args) {
        String str = "<xml><appid><![CDATA[wxbe946decfb1f6b39]]></appid>\n" +
                "<attach><![CDATA[JSAPI_1]]></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[1484872062]]></mch_id>\n" +
                "<nonce_str><![CDATA[1628218368829]]></nonce_str>\n" +
                "<openid><![CDATA[o2hSd5SiqTepOmjAqeFkd_wuCDdY]]></openid>\n" +
                "<out_trade_no><![CDATA[400004590002_JSAPI]]></out_trade_no>\n" +
                "<result_code><![CDATA[SUCCESS]]></result_code>\n" +
                "<return_code><![CDATA[SUCCESS]]></return_code>\n" +
                "<sign><![CDATA[400CFA8230033F0E617E8A0A6F09186B]]></sign>\n" +
                "<time_end><![CDATA[20210806105253]]></time_end>\n" +
                "<total_fee>1</total_fee>\n" +
                "<trade_type><![CDATA[JSAPI]]></trade_type>\n" +
                "<transaction_id><![CDATA[4200001119202108063847812831]]></transaction_id>\n" +
                "</xml>\n";

        WxPayCallbackVO payCallVO = convertToObject(str, WxPayCallbackVO.class);
        System.out.println(payCallVO.toString());
    }

}
