Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions util.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,22 @@ func XmlToMap(xmlStr string) Params {
decoder := xml.NewDecoder(strings.NewReader(xmlStr))

var (
key string
value string
key *string
value *string
)

for t, err := decoder.Token(); err == nil; t, err = decoder.Token() {
switch token := t.(type) {
case xml.StartElement: // 开始标签
key = token.Name.Local
key = &token.Name.Local
case xml.CharData: // 标签内容
content := string([]byte(token))
value = content
}
if key != "xml" {
if value != "\n" {
params.SetString(key, value)
value = &content
case xml.EndElement: // 结束标签
if key != nil && value != nil && *key != "xml" {
params.SetString(*key, *value)
key = nil
value = nil
}
}
}
Expand Down
37 changes: 37 additions & 0 deletions util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package wxpay

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestXmlToMap(t *testing.T) {
Expand All @@ -13,6 +15,41 @@ func TestXmlToMap(t *testing.T) {
t.Log(params)
}

func TestXmlToMapWithLineBreaksAndSpaces(t *testing.T) {
xmlStr := `<xml>
<appid><![CDATA[wx2421b1c4370ec43b]]></appid>
<attach><![CDATA[支付测试]]></attach>
<bank_type><![CDATA[CFT]]></bank_type>
<fee_type><![CDATA[CNY]]></fee_type>
<is_subscribe><![CDATA[Y]]></is_subscribe>
<mch_id><![CDATA[10000100]]></mch_id>
<nonce_str><![CDATA[5d2b6c2a8db53831f7eda20af46e531c]]></nonce_str>
<openid><![CDATA[oUpF8uMEb4qRXf22hE3X68TekukE]]></openid>
<out_trade_no><![CDATA[1409811653]]></out_trade_no>
<result_code><![CDATA[SUCCESS]]></result_code>
<return_code><![CDATA[SUCCESS]]></return_code>
<sign><![CDATA[B552ED6B279343CB493C5DD0D78AB241]]></sign>
<time_end><![CDATA[20140903131540]]></time_end>
<total_fee>1</total_fee>
<coupon_fee><![CDATA[10]]></coupon_fee>
<coupon_count><![CDATA[1]]></coupon_count>
<coupon_type><![CDATA[CASH]]></coupon_type>
<coupon_id><![CDATA[10000]]></coupon_id>
<trade_type><![CDATA[JSAPI]]></trade_type>
<transaction_id><![CDATA[1004400740201409030005092168]]></transaction_id>
</xml>
`
params := XmlToMap(xmlStr)
if params == nil {
t.Error(params)
}
t.Log(params)

assert.Equal(t, "wx2421b1c4370ec43b", params["appid"])
assert.Equal(t, "支付测试", params["attach"])
assert.Equal(t, "1004400740201409030005092168", params["transaction_id"])
}

func TestMapToXml(t *testing.T) {
params := map[string]string{"return_msg": "OK", "appid": "wx2421b1c4370ec43b", "mch_id": "10000100"}
xmlStr := MapToXml(params)
Expand Down