go - Correct use of XML annotations, fields and structs in custom UnmarshalXML function -
consider following struct:
type mystruct struct { name string meta map[string]interface{} }
which has following unmarshalxml function:
func (m *mystruct) unmarshalxml(d *xml.decoder, start xml.startelement) error { var v struct { xmlname xml.name //`xml:"mystruct"` name string `xml:"name"` meta struct { inner []byte `xml:",innerxml"` } `xml:"meta"` } err := d.decodeelement(&v, &start) if err != nil { return err } m.name = v.name mymap := make(map[string]interface{}) // ... mxj magic here ... - temp := v.meta.inner prefix := "<meta>" postfix := "</meta>" str := prefix + string(temp) + postfix //fmt.println(str) mymxjmap, err := mxj.newmapxml([]byte(str)) mymap = mymxjmap // fill mymap //m.meta = mymap m.meta = mymap["meta"].(map[string]interface{}) return nil }
my problem code these lines:
prefix := "<meta>" postfix := "</meta>" str := prefix + string(temp) + postfix mymxjmap, err := mxj.newmapxml([]byte(str)) mymap = mymxjmap //m.meta = mymap m.meta = mymap["meta"].(map[string]interface{})
my question how make correct use of xml annotations (,innerxml etc), fields , structs, don't have manually pre-/append <meta></meta>
tags afterwards whole meta field single map.
the full code example here: http://play.golang.org/p/q4_tryubo6
xml
package doesn't provide way unmarshal xml map[string]interface{}
because there no single way , in cases not possible. map doesn't preserve order of elements (that important in xml) , doesn't allow elements duplicate keys.
mxj
package used in example has rules how unmarshal arbitrary xml go map. if requirements not conflict these rules can use mxj
package parsing , not use xml
package @ all:
// skipping error handling here m, _ := mxj.newmapxml([]byte(s)) mm := m["mystruct"].(map[string]interface{}) mystruct.name = mm["name"].(string) mystruct.meta = mm["meta"].(map[string]interface{})
full example: http://play.golang.org/p/acpuas0qmj
Comments
Post a Comment