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

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

Susan Sarandon
Release: 2024-12-05 03:15:11
Original
158 people have browsed it

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

Unmarshal XML Directly Into a Map

When dealing with large XML datasets, the dual conversion process of unmarshaling into a struct and then into a map can become time-consuming. This article explores a more efficient approach to directly unmarshal XML into a map.

Problem:

The goal is to convert the following XML into a map[string]string, where the key-value pairs are extracted from child elements:

<classAccesses>
    <apexClass>AccountRelationUtility</apexClass>
    <enabled>true</enabled>
</classAccesses>
Copy after login

To achieve this, a custom data structure that implements the xml.Unmarshaller interface is required.

Solution:

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: parse the inner structure

        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

By implementing the xml.Unmarshaller interface, the custom data structure can directly unmarshal the XML into a map[string]string. This eliminates the need for the intermediate struct conversion, resulting in a more efficient unmarshaling process.

Partial Solution and Demonstration:

A partial solution demonstrating the approach is available at https://play.golang.org/p/7aOQ5mcH6zQ. This solution includes the custom data structure and a sample XML to demonstrate the unmarshaling process.

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