美文网首页
golang map转xml

golang map转xml

作者: 王哈哈就很棒 | 来源:发表于2020-03-24 18:16 被阅读0次
    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))
    }
    
    

    相关文章

      网友评论

          本文标题:golang map转xml

          本文链接:https://www.haomeiwen.com/subject/obrayhtx.html