objcoding/wxpay

XmlToMap 这个方法有bug,当xml 前面有空格的时候,返回的map为空

xyy11070 opened this issue · 1 comments

str := `<xml>
   <trade_type><![CDATA[APP]]></trade_type>
   <prepay_id><![CDATA[wx20190506151427404120]]></prepay_id>
   <nonce_str><![CDATA[1557126867008139000]]></nonce_str>
   <return_code><![CDATA[SUCCESS]]></return_code>
   <err_code_des><![CDATA[ok]]></err_code_des>
   <sign><![CDATA[3C323ECE220CC631240E874F80C3737D]]></sign>
   <mch_id><![CDATA[1225268501]]></mch_id>
   <return_msg><![CDATA[OK]]></return_msg>
   <appid><![CDATA[wxe353414396c4b931]]></appid>
   <device_info><![CDATA[sandbox]]></device_info>
   <result_code><![CDATA[SUCCESS]]></result_code>
   <err_code><![CDATA[SUCCESS]]></err_code>
 </xml>`
	mp := wxpay.XmlToMap(str)

I fixed this bug, for anyone who are bothered by this problem, here is the code, it's actually very simple:

func XmlToMap(xmlStr string) Params {

	params := make(Params)
	decoder := xml.NewDecoder(strings.NewReader(xmlStr))

	var (
		key   string
		value string
	)

    inBetween := false
    for t, err := decoder.Token(); err == nil; t, err = decoder.Token() {
        switch token := t.(type) {
        case xml.StartElement:
            key = token.Name.Local
            if key == "xml" {
                continue
            }
            inBetween = true
        case xml.CharData:
            if !inBetween {
                continue
            }
            value = string([]byte(token))
            params[key] = value
        case xml.EndElement:
            inBetween = false
        }

    }

	return params
}