Home >Backend Development >Golang >Can XML be Unmarhaled Directly into a Go Map to Improve Performance?

Can XML be Unmarhaled Directly into a Go Map to Improve Performance?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-03 13:33:14219browse

Can XML be Unmarhaled Directly into a Go Map to Improve Performance?

Unmarshaling XML Directly Into a Map

Problem:

Unmarshalling XML into a struct and then converting it into a map is time-consuming for large datasets. Is there a way to unmarshal directly into a map?

XML:

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

Current Struct:

type classAccesses struct {
    ApexClass string `xml:"apexClass"`
    Enabled   string `xml:"enabled"`
}

type diffs struct {
    ClassAccesses []classAccesses `xml:"classAccesses"`
}

Desired Map:

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

Solution:

Implement the xml.Unmarshaller interface to marshal data directly into a map[string]string.

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) {

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

Partial Solution:

Visit https://play.golang.org/p/7aOQ5mcH6zQ for a partial implementation.

The above is the detailed content of Can XML be Unmarhaled Directly into a Go Map to Improve Performance?. 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