尝试理解为xml创建自定义marshaller的方法,结构如下:
<Appointment>
<Date>2004-12-22</Date>
<Time>14:00</Time>
</Appointment>
我想的是:
type Appointment struct {
DateTime time.Time `xml:"???"`
}
问题是,我会把什么代替?将单个字段保存到两个不同的xml标记中?
答案 0 :(得分:3)
复杂的编组/解编行为通常需要满足Marshal / Unmarshal接口(这与XML,JSON以及类似的设置类型相同)。
您需要使用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>
答案 1 :(得分:0)
快速猜测,你不能。您应该使用xml.Marshaler
类型...
Appointment
界面