"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Marshal Maps to XML in Go: What to Do When You Get the \"xml: unsupported type: map[string]int\" Error?

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

Published on 2024-11-08
Browse:344

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:

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()
}

Once you have implemented MarshalXML, you can simply call xml.MarshalIndent on your data to generate the desired XML output.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3