英文:
Golang - Marshaling XML time.Time as date format for XML attribute
问题
我正在尝试格式化一个自定义的时间类型Date,它实现了Marshaler接口,并在写入XML时将自身格式化为"2006-01-02"。
我参考了这个Stack Overflow的帖子,但是出现了错误 - &xml.UnsupportedTypeError{Type:(*reflect.rtype)}。
我可能漏掉了什么,有什么想法吗?
英文:
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?
答案1
得分: 6
你正在实现错误的接口。
由于 Date 类型是作为属性进行编组的(如 xml:"DOB,attr"
标签所示),它需要实现 xml.MarshalerAttr 接口:
type MarshalerAttr interface {
MarshalXMLAttr(name Name) (Attr, error)
}
所以你可能需要添加类似以下的代码:
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
}
请注意,我从值字符串中删除了明显不必要的引号。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论