Is there any reason this *shouldn't* work? ( I realize it doesn't, just curious since you can marshal an empty interface ).
type Person struct {
XMLName xml.Name `xml:"person"`
FirstName string `xml:"firstname"`
Parents interface{} `xml:"parent"`
}
func main() {
type Parent struct {
FirstName string `xml:"name"`
LastName string `xml:"lastname"`
}
p := &Person{FirstName: "Steve"}
p.Parents = []Parent{Parent{"Jack","Doe"}, Parent{"Lynne","Doe"}}
data, err := xml.Marshal(p)
if err != nil {
fmt.Println(err)
}
fmt.Println("Marshalled:",string(data))
p2 := &Person{}
p2.Parents = []Parent{}
err = xml.Unmarshal(data, p2)
if err != nil {
fmt.Println(err)
}
fmt.Println("Unmarshalled:", p2)
}
I get that by being an empty interface{}, there are no fields that are exported for it to look at. Except that I'm assigning a concrete type to the interface{}, so shouldn't Unmarshal be able to reflect that interface{} and find the struct/tag names to Unmarshal the data? I'm assuming ( and guessing I'm wrong ) that that's how Marshal does it? I think I'd probably be less confused if Marshal wasn't working as well, but I don't get why Marshal can deal with a interface{} and Unmarshal can't.
The real use case I have being that the XML response I'm getting has some static elements and then it has dynamic elements:
<api>
<staticfield1>data</staticfield1>
<staticfield2>data</staticfield2>
<record>
<fieldname1>data</fieldname1>
<fieldname2>data</fieldname2>
</record>
<record>
..
</record>
</api>
I have the static fields in a struct, but fieldname's returned in the record elements change, depending on which database table is being returned by the api. I want to be able to create a record struct that matches what I know the record will look like for each call, and then compose the whole struct ( static fields + the dynamic fields ) that I'm unmarshalling into.
The solution I have right now is to have a byte array that captures the innerxml and then unmarshal that separately, but I felt like this would be a cleaner solution. (
https://play.golang.org/p/z3BS6tjqgW )
If there isn't anyway to do this - is there anyway to grab a whole <parent> record, with the <parent></parent> tags included? My byte solution works, but the issue I run into is that my innerxml field just ends up with <FirstName></FirstName><LastName></LastName>, with no surrounding <parent> tags. So I have to add the parent tags back so that I can unmarshal to a Parent struct, as you can see in the example.
Any help appreciated!
Steve