I'm trying to format a custom time type, Date, that implements the Marshaler interface and simply formats itself as "2006-01-02" when written as XML.
type Person struct {
...
DateOfBirth Date `xml:"DOB,attr"`
...
}
type Date time.Time
func (d Date) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
dateString := fmt.Sprintf("\"%v\"", time.Time(d).Format("2006-01-02"))
e.EncodeElement(dateString, start)
return nil
}
I was using this SO as a reference, but the error - &xml.UnsupportedTypeError{Type:(*reflect.rtype)} - is thrown.
I'm missing something, any ideas?
You are implementing the wrong interface.
Since the Date type is meant to be marshaled as an attribute (as shown from the xml:"DOB,attr"
tag), it needs to implement the xml.MarshalerAttr interface:
type MarshalerAttr interface {
MarshalXMLAttr(name Name) (Attr, error)
}
So you probably need to add code like this:
func (d Date) MarshalXMLAttr(name xml.Name) (xml.Attr, error) {
dateString := time.Time(d).Format("2006-01-02")
attr := xml.Attr {
name,
dateString,
}
return attr, nil
}
Note that I removed the apparently unnecessary quotes from the value string.