2 回答
TA贡献1794条经验 获得超8个赞
复杂的编组/解组行为通常需要满足 Marshal/Unmarshal 接口(对于 XML、JSON 和 go 中的类似设置类型也是如此)。
您需要xml.Marshaler使用MarshalXML()函数来满足接口,如下所示:
package main
import (
"encoding/xml"
"fmt"
"time"
)
type Appointment struct {
DateTime time.Time
}
type appointmentExport struct {
XMLName struct{} `xml:"appointment"`
Date string `xml:"date"`
Time string `xml:"time"`
}
func (a *Appointment) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
n := &appointmentExport{
Date: a.DateTime.Format("2006-01-02"),
Time: a.DateTime.Format("15:04"),
}
return e.Encode(n)
}
func main() {
a := &Appointment{time.Now()}
output, _ := xml.MarshalIndent(a, "", " ")
fmt.Println(string(output))
}
// prints:
// <appointment>
// <date>2016-04-15</date>
// <time>17:43</time>
// </appointment>
- 2 回答
- 0 关注
- 122 浏览
添加回答
举报