dptgpyl61857413 2015-06-19 01:00
浏览 71
已采纳

如何在Go中将自定义格式的时间序列化到xml中/从xml序列化?

When serializing a datetime to/from xml how do I make it use a custom time format?

  • 写回答

2条回答 默认 最新

  • dst3605528 2015-06-19 14:53
    关注

    Just as you'd implement json.Marshaler and json.Unmarshaler for doing this with JSON (there are many posts about that on StackOverflow and the internet); one way is to implement a custom time type that implements encoding.TextMarshaler and encoding.TextUnmarshaler.

    Those interfaces are used by encoding/xml when encoding items (after first checking for the more specific xml.Marshaler or xml.Unmarshaler interfaces, however those later ones have to do full XML encoding themselves).

    E.g. something like (full example on the <kbd>Go Playground</kbd>):

    const fixedFormat = "Mon Jan 02 2006"
    
    type myTime1 struct {
        time.Time
    }
    
    func (m myTime1) MarshalText() ([]byte, error) {
        text := m.Time.Format(fixedFormat)
        return []byte(text), nil
    }
    func (m *myTime1) UnmarshalText(text []byte) error {
        t, err := time.Parse(fixedFormat, string(text))
        if err == nil {
            m.Time = t
        }
        return err
    }
    

    or

    type myTime2 time.Time
    
    func (m myTime2) MarshalText() ([]byte, error) {
        text := time.Time(m2).Format(fixedFormat)
        return []byte(text), nil
    }
    func (m *myTime2) UnmarshalText(text []byte) error {
        t, err := time.Parse(fixedFormat, string(text))
        if err == nil {
            *m = myTime2(t)
        }
        return err
    }
    

    Either of those can be used in place of time.Time as part of a larger data structure used with xml (un)marshalling. E.g.:

    type Foo struct {
        Date1 myTime1 `xml:"date1"`
        Date2 myTime2 `xml:"date2"`
    }
    

    The difference in how these custom time types are defined changes how you use them with regular time.Time values. E.g.

    m1 := myTime1{time.Now()}
    fmt.Println(m1)
    if m1.Before(time.Now()) {}
    t1 := m1.Time
    // compared to:
    m2 := myTime2(time.Now())
    fmt.Println(time.Time(m2))
    if time.Time(m2).Before(time.Now()) {}
    t2 := time.Time(m2)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line