Home >Backend Development >Golang >How to Convert a Go Map to XML Data?

How to Convert a Go Map to XML Data?

Linda Hamilton
Linda HamiltonOriginal
2024-11-01 18:12:02417browse

How to Convert a Go Map to XML Data?

Marshall Maps to XML in Go

When attempting to convert a map to XML data, an error may be encountered:

xml: unsupported type: map[string]int

While it is straightforward to marshal maps to JSON, using a struct may not be the only option.

To resolve this issue, the xml.Marshaler interface can be utilized:

<code class="go">// Marshal maps 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>

By implementing the MarshalXML method for a custom StringMap type, the map can be marshalled as XML.

To use the marshalled XML:

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

The above is the detailed content of How to Convert a Go Map to XML Data?. 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