Golang – 将 time.Time 作为日期格式进行 XML 属性的编组

huangapple go评论83阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2016年4月14日 03:30:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/36607875.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定