Search code examples
xmlgomarshalling

Marshall map to XML in Go


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

xml: unsupported type: map[string]int

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?


Solution

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

    Source: https://gist.github.com/jackspirou/4477e37d1f1c043806e0

    Now the map can be marshalled by simply calling

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