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

Trying to understand a way to create custom marshaller for xml structured as:

<Appointment>
<Date>2004-12-22</Date>
<Time>14:00</Time>
</Appointment>

I'm thinking of something like:

type Appointment struct {
    DateTime time.Time `xml:"???"`
}

Question is, what would i put instead of ??? to have a single field be saved into two different xml tags?

Quick guess, you can't. You should implement the xml.Marshaler interface with your Appointment type…

Complex marshaling/unmarshaling behavior generally requires satisfying a Marshal/Unmarshal interface (this is of true of XML, JSON, and similarly setup types in go).

You'd need to satisfy the xml.Marshaler interface with a MarshalXML() function, something like the following:

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>