golang map转xml

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))
}

posted @ 2020-06-05 06:09  HaimaBlog  阅读(762)  评论(0编辑  收藏  举报