Home >Backend Development >Golang >How Can I Efficiently Unmarshal XML Directly into a Go Map?

How Can I Efficiently Unmarshal XML Directly into a Go Map?

Barbara Streisand
Barbara StreisandOriginal
2024-12-18 01:53:10265browse

How Can I Efficiently Unmarshal XML Directly into a Go Map?

Unmarshaling XML Directly into a Map

Unmarshaling XML data into an intermediate struct that is then converted into a map can be time-consuming for large data sets. In such cases, direct unmarshaling into a map is a more efficient approach.

To unmarshal XML directly into a map, you can create a custom type that implements the xml.Unmarshaler interface. This type will handle the unmarshaling process and store the data in a map[string]string.

Example:

type classAccessesMap struct {
    m map[string]string
}

// UnmarshalXML implements the xml.Unmarshaler interface to unmarshal XML directly into the map.
func (c *classAccessesMap) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
    c.m = map[string]string{}

    key := ""
    val := ""

    // Iteratively parse XML tokens.
    for {
        t, _ := d.Token()
        switch tt := t.(type) {

        // TODO: Handle the inner structure parsing here.

        case xml.StartElement:
            key = tt.Name.Local

        case xml.EndElement:
            // Store the key-value pair in the map when the end of the "enabled" element is reached.
            if tt.Name.Local == "enabled" {
                c.m[key] = val
            }

            // Return nil when the end of the "classAccesses" element is reached.
            if tt.Name == start.Name {
                return nil
            }
        }
    }
}

Usage:

// Unmarshal the XML into the custom classAccessesMap type.
var classAccessesMap classAccessesMap
if err := xml.Unmarshal([]byte(xmlData), &classAccessesMap); err != nil {
    // Handle error
}

fmt.Println(classAccessesMap.m) // Prints the map containing the parsed data.

The above is the detailed content of How Can I Efficiently Unmarshal XML Directly into a Go Map?. 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