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 關注
- 142 瀏覽
添加回答
舉報