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

How to Directly Unmarshal XML into a Go Map?

Linda Hamilton
Release: 2024-12-10 18:08:11
Original
683 people have browsed it

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

Desired Map:

map[string]string{
    "ApexClass": "enabled"
}
Copy after login

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

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

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!

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