Home >Backend Development >Golang >How to Directly Unmarshal XML into a Go Map?

How to Directly Unmarshal XML into a Go Map?

Linda Hamilton
Linda HamiltonOriginal
2024-12-10 18:08:11682browse

How to Directly Unmarshal XML into a Go Map?

Unmarshal XML Directly into a Map

Problem:

You need to unmarshal XML data into a map instead of first unmarshalling into a struct and then converting the struct into a map, which is taking too much time for a large dataset.

<classAccesses>
    <apexClass>AccountRelationUtility</apexClass>
    <enabled>true</enabled>
</classAccesses>

Desired Map:

map[string]string{
    "ApexClass": "enabled"
}

Solution:

Implement the xml.Unmarshaller interface for a custom type that represents the desired map structure:

type classAccessesMap struct {
    m map[string]string
}

func (c *classAccessesMap) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
    c.m = map[string]string{}

    key := ""
    val := ""

    for {
        t, _ := d.Token()
        switch tt := t.(type) {

        // TODO: ...

        case xml.StartElement:
            fmt.Println(">", tt)

        case xml.EndElement:
            fmt.Println("<", tt)
            if tt.Name == start.Name {
                return nil
            }

            if tt.Name.Local == "enabled" {
                c.m[key] = val
            }
        }
    }
}

Then, use the xml.Unmarshal function to parse the XML data directly into the custom type:

var classAccesses classAccessesMap
if err := xml.Unmarshal(data, &classAccesses); err != nil {
    // Handle error
}

fmt.Println(classAccesses.m)

The above is the detailed content of How to Directly Unmarshal XML 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