Home > Article > Backend Development > How to Convert Go Maps to XML: A Custom Marshaler Approach
Marshall Go Maps to XML
Converting Go maps to JSON is straightforward. However, attempting to perform the same operation for XML can lead to an error:
xml: unsupported type: map[string]int
Solution: Using a Custom XML Marshaler
Unlike JSON, XML marshalling does not inherently support maps. To work around this limitation, a custom xml.Marshaler can be implemented for your map type:
<code class="go">// 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() }</code>
Now, you can simply call xml.MarshalIndent(...) to marshal the map into XML:
<code class="go">output, err := xml.MarshalIndent(data, "", " ")</code>
The above is the detailed content of How to Convert Go Maps to XML: A Custom Marshaler Approach. For more information, please follow other related articles on the PHP Chinese website!