How to Marshal Maps to XML in Go: What to Do When You Get the \'xml: unsupported type: map[string]int\' Error?

Mary-Kate Olsen
Release: 2024-11-03 11:17:02
Original
431 people have browsed it

How to Marshal Maps to XML in Go: What to Do When You Get the

Marshalling Maps to XML in Go

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

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!

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