Using the xml
package in golang I\'m having trouble unmarshalling a list of non-homogenous types. Consider the following XML document whose nested elements are a l
As pointed out by other comments, the decoder cannot deal with interface fields without some help. Implementing xml.Unmarshaller
on the container will make it do what you want (full working example on the playground):
func (md *MyDoc) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
md.XMLName = start.Name
// grab any other attrs
// decode inner elements
for {
t, err := d.Token()
if err != nil {
return err
}
var i Item
switch tt := t.(type) {
case xml.StartElement:
switch tt.Name.Local {
case "foo":
i = new(Foo) // the decoded item will be a *Foo, not Foo!
case "bar":
i = new(Bar)
// default: ignored for brevity
}
// known child element found, decode it
if i != nil {
err = d.DecodeElement(i, &tt)
if err != nil {
return err
}
md.Items = append(md.Items, i)
i = nil
}
case xml.EndElement:
if tt == start.End() {
return nil
}
}
}
return nil
}
This is just an implementation of what @evanmcdonnal suggests. All this does is instantiate the proper Item
based on the name of the next Token, then call d.DecodeElement()
with it (i.e. let the xml decoder do the heavy lifting).
Note that the unmarshalled Items
are pointers. You'll need to do some more work if you want values. This also needs to be expanded some more for proper handling of errors or unexpected input data.