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条)

报告相同问题?

悬赏问题

  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来