The problem is that xml.Unmarshal of a struct with a field of type map[string]interface{} will fail with the error:
unknown type map[string]interface {}
{XMLName:{Space: Local:myStruct} Name:test Meta:map[]}
Since the Meta field of type map[string]interface{} is as far as I can define, what's inside has to be dynamically unmarshalled.
package main
import (
"encoding/xml"
"fmt"
)
func main() {
var myStruct MyStruct
// meta is as far as we know, inside meta, dynamic properties and nesting will happen
s := `<myStruct>
<name>test</name>
<meta>
<someProp>something</someProp>
<someOtherDynamic>
<name>test</name>
<somethingElse>test2</somethingElse>
<nested3>
<name>nested3</name>
<nested3elements>
<elem>ele1</elem>
<elem>ele2</elem>
</nested3elements>
</nested3>
</someOtherDynamic>
</meta>
</myStruct>`
err := xml.Unmarshal([]byte(s), &myStruct)
if err == nil {
fmt.Printf("%+v
", myStruct)
} else {
fmt.Println(err)
fmt.Printf("%+v
", myStruct)
}
}
type MyStruct struct {
XMLName xml.Name `xml:"myStruct"`
Name string `xml:"name"`
Meta map[string]interface{} `xml:"meta,omitempty"`
}
I've made an example here: http://play.golang.org/p/lTDJzXXPwT
How can I achieve this?
My workaround "solution" so far:
http://play.golang.org/p/gQUlvkYl7k
Basically what happens is that:
- The Meta field got the xml annotations removed, thus being ignore from the xml.Unmashal
- New type, MapContainer, is created with a field: InnerXML []byte
xml:",innerxml"
- MetaByte field of type MapContainer is added using the
xml:"meta,omitempty"
annotations
So in the first xml.Unmarshal we save a byte slice of the meta element's XML. Then in our custom xml unmarshal function we take that byteSlice and use the magic function NewMapXml from the mxj package, and set the Meta field of the struct to this newly created map.
This is possible thanks to the genius made this repo, https://github.com/clbanning/mxj , which can unmarshal from XML to maps.
Updated current best solution:
http://play.golang.org/p/_tw06klods
Thanks to Adam Vincze