Created
January 4, 2021 02:10
-
-
Save acomagu/3c2d20fe1a58f1083ee6edee78e896e1 to your computer and use it in GitHub Desktop.
The map[string]interface implementing XMLMarshaller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package xml_marshallable_map | |
// XMLMarshallableMap contains nestable data and implements | |
// XMLMarshaller. The actual type of interface{} part must be string or | |
// map[string]interface{}. The fields are sorted in alphabetical | |
// order and encoded. | |
type XMLMarshallableMap map[string]interface{} | |
func (m XMLMarshallableMap) MarshalXML(e *xml.Encoder, start xml.StartElement) error { | |
if err := e.EncodeToken(start); err != nil { | |
return err | |
} | |
var keys []string | |
for k := range m { | |
keys = append(keys, k) | |
} | |
sort.Strings(keys) | |
for _, k := range keys { | |
childStart := xml.StartElement{Name: xml.Name{Local: k}} | |
switch v := m[k].(type) { | |
case string: | |
if err := e.EncodeElement(v, childStart); err != nil { | |
return err | |
} | |
case map[string]interface{}: | |
if err := XMLMarshallableMap(v).MarshalXML(e, childStart); err != nil { | |
return err | |
} | |
default: | |
panic(fmt.Sprintf("the type of value of parameters must be string or map[string]interface{}, but %+v", v)) | |
} | |
} | |
return e.EncodeToken(start.End()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment