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

How to Convert a Go Map to XML Data?

Linda Hamilton
Release: 2024-11-01 18:12:02
Original
416 people have browsed it

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

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

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

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!

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