Home >Backend Development >Golang >How Can I Directly Unmarshal XML into a Go Map for Optimized Data Processing?

How Can I Directly Unmarshal XML into a Go Map for Optimized Data Processing?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-05 16:21:111038browse

How Can I Directly Unmarshal XML into a Go Map for Optimized Data Processing?

Directly Unmarshal XML into a Map

Unmarshalling XML directly into a map can optimize data processing by eliminating the intermediate struct conversion step.

Implementation:

To achieve this, create a type that implements the xml.Unmarshaller interface, allowing direct mapping of XML data into a map[string]string.

type classAccessesMap struct {
    m map[string]string
}

// UnmarshalXML implements the xml.Unmarshaller interface
func (c *classAccessesMap) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
    c.m = make(map[string]string)

    var key, val string

    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
            }
        }
    }
}

Usage:

Apply the custom type to the unmarshal operation to directly map the XML data into a map:

// Unmarshalling into a map
var cm classAccessesMap
err := xml.Unmarshal([]byte(`<classAccesses>\n    <apexClass>AccountRelationUtility</apexClass>\n    <enabled>true</enabled>\n</classAccesses>`), &cm)
if err != nil {
    fmt.Println(err)
}

This approach streamlines data processing by avoiding the overhead of dual conversions, resulting in improved performance for large data sets.

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