Home >Backend Development >Golang >How Can I Efficiently Unmarshal XML Directly into a Go Map?
Unmarshaling XML data into an intermediate struct that is then converted into a map can be time-consuming for large data sets. In such cases, direct unmarshaling into a map is a more efficient approach.
To unmarshal XML directly into a map, you can create a custom type that implements the xml.Unmarshaler interface. This type will handle the unmarshaling process and store the data in a map[string]string.
Example:
type classAccessesMap struct { m map[string]string } // UnmarshalXML implements the xml.Unmarshaler interface to unmarshal XML directly into the map. func (c *classAccessesMap) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { c.m = map[string]string{} key := "" val := "" // Iteratively parse XML tokens. for { t, _ := d.Token() switch tt := t.(type) { // TODO: Handle the inner structure parsing here. case xml.StartElement: key = tt.Name.Local case xml.EndElement: // Store the key-value pair in the map when the end of the "enabled" element is reached. if tt.Name.Local == "enabled" { c.m[key] = val } // Return nil when the end of the "classAccesses" element is reached. if tt.Name == start.Name { return nil } } } }
Usage:
// Unmarshal the XML into the custom classAccessesMap type. var classAccessesMap classAccessesMap if err := xml.Unmarshal([]byte(xmlData), &classAccessesMap); err != nil { // Handle error } fmt.Println(classAccessesMap.m) // Prints the map containing the parsed data.
The above is the detailed content of How Can I Efficiently Unmarshal XML Directly into a Go Map?. For more information, please follow other related articles on the PHP Chinese website!