Skip to content

Commit

Permalink
Merge pull request #78 from ArtisanCloud/develop
Browse files Browse the repository at this point in the history
refact(xml): recursively Map2XML
  • Loading branch information
Matrix-X authored Apr 3, 2023
2 parents 1dd9932 + 5d7c18d commit c3a695a
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 8 deletions.
22 changes: 14 additions & 8 deletions object/xml.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,31 +14,38 @@ func Str2Xml(in string) string {
return b.String()
}

func Map2Xml(obj *HashMap) (strXML string) {
func Map2Xml(obj *HashMap, isSub bool) (strXML string) {

for k, v := range *obj {
switch v.(type) {
case string:
strXML = strXML + fmt.Sprintf("<%s><![CDATA[%s]]></%s>", k, v, k)
break
case int:
case int8:
case int16:
case int32:
case int64:
case int, int8, int16, int32, int64:
strXML = strXML + fmt.Sprintf("<%s>%d</%s>", k, v, k)
break
case float32:
case float64:
strXML = strXML + fmt.Sprintf("<%s>%f</%s>", k, v, k)
break
case *HashMap:
strXML = strXML + fmt.Sprintf("<%s>%s</%s>", k, Map2Xml(v.(*HashMap), true), k)
break
case HashMap:
val := v.(HashMap)
strXML = strXML + fmt.Sprintf("<%s>%s</%s>", k, Map2Xml(&val, true), k)
break
case interface{}:
b, _ := json.Marshal(v)
strXML = strXML + fmt.Sprintf("<%s><![CDATA[%s]]></%s>", k, string(b), k)
break
}
}
return "<xml>" + strXML + "</xml>"
if isSub {
return strXML
} else {
return "<xml>" + strXML + "</xml>"
}
}

func StringMap2Xml(obj *StringMap) (strXML string) {
Expand All @@ -49,7 +56,6 @@ func StringMap2Xml(obj *StringMap) (strXML string) {
return "<xml>" + strXML + "</xml>"
}


func Xml2Map(b []byte) (m HashMap, err error) {

decoder := xml.NewDecoder(bytes.NewReader(b))
Expand Down
42 changes: 42 additions & 0 deletions object/xml_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,48 @@ import (
"testing"
)

func Test_Map2Xml(t *testing.T) {

obj := HashMap{
"ActName": "红包测试",
"ClientIp": "127.0.0.1",
"MchBillno": "1634802770-845085000",
"MchID": "1613495874",
"NonceStr": "sy5ViKYvvT",
"ReOpenid": "okQfd5UNMMbDEyJo2ydwsGQ9R4NI",
"Remark": "猜越多得越多,快来抢!",
"RiskInfo": "",
"SceneID": "",
"SendName": "技术部-王秦文",
"Sign": "581E208372C7F3BACCD81D0458BEAF33AC293B9E88E9EA806C8AC901D55831CE",
"Text": "",
"Array": &HashMap{
"key1": "value",
"keyArray": HashMap{
"key2": 123,
},
},
"ArrayStr": StringMap{
"key1": "value",
},
"ArrayStrP": &StringMap{
"key1": "value",
},
"TotalAmount": "1000",
"TotalNum": "1",
"Wishing": "技术部测试红包",
"Wxappid": "wx94dcb1e3674e84ad",
"XMLName": "",
"cert": "/private/var/www/html/GO/连续剧待有代币的版本/keys/1613495874/apiclient_cert.pem",
"ssl_key": "/private/var/www/html/GO/连续剧待有代币的版本/keys/1613495874/apiclient_key.pem",
}

xmlObj := Map2Xml(&obj, false)
println(xmlObj)
fmt.Dump(xmlObj)

}

func Test_StringMap2Xml(t *testing.T) {

obj := StringMap{
Expand Down

0 comments on commit c3a695a

Please sign in to comment.