package main
import (
"encoding/xml"
"fmt"
)
type MyMap map[string]interface{}
type xmlMapEntry struct {
XMLName xml.Name
Value interface{} `xml:",chardata"`
}
// map转xml
func (m MyMap) 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 main() {
m := make(map[string]interface{})
m["name"] = "wang"
m["age"] = 25
buf, _ := xml.Marshal(MyMap(m))
fmt.Println(string(buf))
}
有疑问加站长微信联系(非本文作者)