我最终通过使用
Dave C建议的xml.Marshaler来解决这个问题
// StringMap is a map[string]string. type StringMap map[string]string // StringMap marshals into XML. func (s StringMap) MarshalXML(e *xml.Encoder,start xml.StartElement) error { tokens := []xml.Token{start} for key,value := range s { t := xml.StartElement{Name: xml.Name{"",key}} tokens = append(tokens,t,xml.CharData(value),xml.EndElement{t.Name}) } tokens = append(tokens,xml.EndElement{start.Name}) for _,t := range tokens { err := e.EncodeToken(t) if err != nil { return err } } // flush to ensure tokens are written err := e.Flush() if err != nil { return err } return nil }
资料来源:https://gist.github.com/jackspirou/4477e37d1f1c043806e0@H_403_4@
output,err := xml.MarshalIndent(data,""," ")