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