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

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

Susan Sarandon
Release: 2024-10-31 08:47:30
Original
243 people have browsed it

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>
Copy after login

Now, you can simply call xml.MarshalIndent(...) to marshal the map into XML:

<code class="go">output, err := xml.MarshalIndent(data, "", "  ")</code>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template