在golang中将单个字段编组为两个标签

试图了解一种为 xml 创建自定义编组器的方法,结构如下:


<Appointment>

<Date>2004-12-22</Date>

<Time>14:00</Time>

</Appointment>

我在想这样的事情:


type Appointment struct {

    DateTime time.Time `xml:"???"`

}

问题是,我会用什么代替???将单个字段保存到两个不同的 xml 标签中?


慕哥9229398
浏览 125回答 2
2回答

幕布斯7119047

复杂的编组/解组行为通常需要满足 Marshal/Unmarshal 接口(对于 XML、JSON 和 go 中的类似设置类型也是如此)。您需要xml.Marshaler使用MarshalXML()函数来满足接口,如下所示:package mainimport (&nbsp; &nbsp; "encoding/xml"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "time")type Appointment struct {&nbsp; &nbsp; DateTime time.Time}type appointmentExport struct {&nbsp; &nbsp; XMLName struct{} `xml:"appointment"`&nbsp; &nbsp; Date&nbsp; &nbsp; string&nbsp; &nbsp;`xml:"date"`&nbsp; &nbsp; Time&nbsp; &nbsp; string&nbsp; &nbsp;`xml:"time"`}func (a *Appointment) MarshalXML(e *xml.Encoder, start xml.StartElement) error {&nbsp; &nbsp; n := &appointmentExport{&nbsp; &nbsp; &nbsp; &nbsp; Date: a.DateTime.Format("2006-01-02"),&nbsp; &nbsp; &nbsp; &nbsp; Time: a.DateTime.Format("15:04"),&nbsp; &nbsp; }&nbsp; &nbsp; return e.Encode(n)}func main() {&nbsp; &nbsp; a := &Appointment{time.Now()}&nbsp; &nbsp; output, _ := xml.MarshalIndent(a, "", "&nbsp; &nbsp; ")&nbsp; &nbsp; fmt.Println(string(output))}// prints:// <appointment>//&nbsp; &nbsp; &nbsp;<date>2016-04-15</date>//&nbsp; &nbsp; &nbsp;<time>17:43</time>// </appointment>

德玛西亚99

快速猜测,你不能。你应该xml.Marshaler用你的Appointment类型实现接口......
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go