How to Marshal a Map to XML in Go: Is a Struct the Only Way?

Barbara Streisand
Release: 2024-10-29 18:31:02
Original
311 people have browsed it

How to Marshal a Map to XML in Go: Is a Struct the Only Way?

Marshall Map to XML in Go

Encountering an error while attempting to marshal a map to XML data? Take a look at this article for a solution.

The popular JSON-to-XML conversion is well-known for utilizing maps. However, when it comes to XML, things take a different turn. You might be left wondering why maps don't behave the same way in both situations. Is it true that using a Struct is the only viable solution here?

Solution

A brilliant solution was found using the xml.Marshaler type. Here's how it works:

  1. Define a StringMap type: Create a custom type to represent your map, dubbed StringMap. This type will have a map[string]string underlying structure.
  2. Implement the MarshalXML method: StringMap should implement the xml.Marshaler interface's MarshalXML method. This method translates a map into XML.
  3. Encode map values: Loop through the map's key-value pairs, generating xml.StartElement tokens for each key and xml.CharData tokens for each value.
  4. Flush and return: To write the XML tokens and flush the buffer, use the encoder's EncodeToken and Flush methods.

Once you've created a custom StringMap type that implements xml.Marshaler, marshalling the map to XML is as simple as:

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

This method provides a convenient way to handle maps in XML marshalling, eliminating the need to resort to Structs.

The above is the detailed content of How to Marshal a Map to XML in Go: Is a Struct the Only Way?. 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