在 Go 中 Marshall 映射到 XML

时间:2023-03-21

浏览:237

作者:佚名

各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题是《在 Go 中 Marshall 映射到 XML》,很明显是关于Golang的文章哈哈哈,其中内容主要会涉及到golang等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

问题内容

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

xml: unsupported type: map[string]int

编组映射适用于 JSON,所以我不明白为什么它不适用于 XML。使用 Struct 真的是唯一的方法吗?

正确答案

我最终通过使用Dave C建议的 xml.Marshaler 解决了这个问题

// 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
    return e.Flush()
}

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

现在可以通过简单地调用来编组地图

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

以上就是《在 Go 中 Marshall 映射到 XML》的详细内容,更多关于golang的资料请关注golang学习网公众号!

本文内容来源于互联网,如有侵权请联系删除。

相关文章

更多

热门专题

更多
首页