diff --git a/util.go b/util.go index 02bc1ca..77526e7 100644 --- a/util.go +++ b/util.go @@ -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 } } } diff --git a/util_test.go b/util_test.go index ebbeaad..49081a4 100644 --- a/util_test.go +++ b/util_test.go @@ -2,6 +2,8 @@ package wxpay import ( "testing" + + "github.com/stretchr/testify/assert" ) func TestXmlToMap(t *testing.T) { @@ -13,6 +15,41 @@ func TestXmlToMap(t *testing.T) { t.Log(params) } +func TestXmlToMapWithLineBreaksAndSpaces(t *testing.T) { + xmlStr := ` + + + + + + + + + + + + + + 1 + + + + + + + +` + 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)