Marshall在Go中映射到XML [英] Marshall map to XML in Go

查看:165
本文介绍了Marshall在Go中映射到XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将地图输出为XML数据,但是我收到以下错误:

I'm trying to output a map as XML data, however I receive the following error:

xml: unsupported type: map[string]int

编组映射对于JSON工作正常,所以我不明白为什么它不会对XML来说工作是一样的。使用Struct真的是唯一的方法吗?

Marshalling maps works fine for JSON so I don't get why it wouldn't work the same for XML. Is using a Struct really the only way?

推荐答案

我最终通过使用xml.Marshaler解决了 Dave C

I ended up solving this by using the xml.Marshaler as suggested by Dave C

// StringMap is a map[string]string.
type StringMap map[string]string

// StringMap marshals into XML.
func (s StringMap) MarshalXML(e *xml.Encoder, start xml.StartElement) error {

    tokens := []xml.Token{start}

    for key, value := range s {
        t := xml.StartElement{Name: xml.Name{"", key}}
        tokens = append(tokens, t, xml.CharData(value), xml.EndElement{t.Name})
    }

    tokens = append(tokens, xml.EndElement{start.Name})

    for _, t := range tokens {
        err := e.EncodeToken(t)
        if err != nil {
            return err
        }
    }

    // flush to ensure tokens are written
    err := e.Flush()
    if err != nil {
        return err
    }

    return nil
}

来源: https://gist.github.com/jackspirou/4477e37d1f1c043806e

现在可以通过简单地调用

Now the map can be marshalled by simply calling

output, err := xml.MarshalIndent(data, "", "  ")

这篇关于Marshall在Go中映射到XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆