go中map与xml不能直接互转,需要自定义map类型并重写MarshalXML()和UnmarshalXML()方法。
stringmap.go
package stringmap
import (
"encoding/xml"
"io"
)
type StringMap map[string]string
type xmlMapEntry struct {
XMLName xml.Name
Value string `xml:",chardata"`
}
func (m StringMap) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
if len(m) == 0 {
return nil
}
err := e.EncodeToken(start)
if err != nil {
return err
}
for k, v := range m {
e.Encode(xmlMapEntry{XMLName: xml.Name{Local: k}, Value: v})
}
return e.EncodeToken(start.End())
}
func (m *StringMap) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
*m = StringMap{}
for {
var e xmlMapEntry
err := d.Decode(&e)
if err == io.EOF {
break
} else if err != nil {
return err
}
(*m)[e.XMLName.Local] = e.Value
}
return nil
}
stringmap_test.go
package stringmap
import (
"testing"
"encoding/xml"
"fmt"
)
func TestName(t *testing.T) {
userMap := make(map[string]string)
userMap["name"] = "Name"
userMap["id"] = "1"
buf, _ := xml.Marshal(StringMap(userMap))
fmt.Println(string(buf))
stringMap := make(map[string]string)
err := xml.Unmarshal(buf, (*StringMap)(&stringMap))
if err != nil {
fmt.Println(err)
}
fmt.Println(stringMap)
}
输出:
<StringMap><name>Name</name><id>1</id></StringMap>
map[name:Name id:1]
欢迎关注我的公众号“彤哥读源码”,查看更多“源码&架构&算法”系列文章, 与彤哥一起畅游源码的海洋。