Home  >  Article  >  Backend Development  >  How to Convert Go Maps to XML: A Custom Marshaler Approach

How to Convert Go Maps to XML: A Custom Marshaler Approach

Susan Sarandon
Susan SarandonOriginal
2024-10-31 08:47:30137browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn