Problem:
You need to unmarshal XML data into a map instead of first unmarshalling into a struct and then converting the struct into a map, which is taking too much time for a large dataset.
<classAccesses> <apexClass>AccountRelationUtility</apexClass> <enabled>true</enabled> </classAccesses>
Desired Map:
map[string]string{ "ApexClass": "enabled" }
Solution:
Implement the xml.Unmarshaller interface for a custom type that represents the desired map structure:
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: ... 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 } } } }
Then, use the xml.Unmarshal function to parse the XML data directly into the custom type:
var classAccesses classAccessesMap if err := xml.Unmarshal(data, &classAccesses); err != nil { // Handle error } fmt.Println(classAccesses.m)
The above is the detailed content of How to Directly Unmarshal XML into a Go Map?. For more information, please follow other related articles on the PHP Chinese website!