When attempting to convert a map to XML data, developers may encounter an error stating "xml: unsupported type: map[string]int." Even though marshalling maps is possible for JSON, it is not supported for XML by default.
One solution to this issue is to utilize the xml.Marshaler interface. By creating a custom StringMap type and implementing MarshalXML, you can control how the map is serialized into XML. This allows you to specify the desired structure and element names.
Here's an example implementation of MarshalXML for a StringMap:
<code class="golang">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>
Once you have implemented MarshalXML, you can simply call xml.MarshalIndent on your data to generate the desired XML output.
The above is the detailed content of How to Marshal Maps to XML in Go: What to Do When You Get the \'xml: unsupported type: map[string]int\' Error?. For more information, please follow other related articles on the PHP Chinese website!