【问题标题】:Golang XML Unmarshal and time.Time fieldsGolang XML Unmarshal 和 time.Time 字段
【发布时间】:2013-06-22 11:24:28
【问题描述】:

我有通过 REST API 检索的 XML 数据,我将其解组到 GO 结构中。其中一个字段是日期字段,但是 API 返回的日期格式与默认时间不匹配。时间解析格式因此解组失败。

有什么方法可以指定 unmarshal 函数在 time.Time 解析中使用哪种日期格式?我想使用正确定义的类型并使用字符串来保存日期时间字段感觉不对。

示例结构:

type Transaction struct {

    Id int64 `xml:"sequencenumber"`
    ReferenceNumber string `xml:"ourref"`
    Description string `xml:"description"`
    Type string `xml:"type"`
    CustomerID string `xml:"namecode"`
    DateEntered time.Time `xml:"enterdate"` //this is the field in question
    Gross float64 `xml:"gross"`
    Container TransactionDetailContainer `xml:"subfile"`
}

返回的日期格式为“yyyymmdd”。

【问题讨论】:

标签: xml-parsing go unmarshalling


【解决方案1】:

我遇到了同样的问题。

time.Time 不满足xml.Unmarshaler 接口。而且您不能指定日期格式。

如果您不想在之后处理解析并且更愿意让xml.encoding 来处理,一种解决方案是创建一个带有匿名time.Time 字段的结构并使用您的自定义实现您自己的UnmarshalXML日期格式。

type Transaction struct {
    //...
    DateEntered     customTime     `xml:"enterdate"` // use your own type that satisfies UnmarshalXML
    //...
}

type customTime struct {
    time.Time
}

func (c *customTime) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
    const shortForm = "20060102" // yyyymmdd date format
    var v string
    d.DecodeElement(&v, &start)
    parse, err := time.Parse(shortForm, v)
    if err != nil {
        return err
    }
    *c = customTime{parse}
    return nil
}

如果您的 XML 元素使用属性作为日期,则必须以相同的方式实现 UnmarshalXMLAttr。

http://play.golang.org/p/EFXZNsjE4a

【讨论】:

  • 这让我走上了正确的道路。当我改为使用 customTime time.Time 时更容易处理 - 无需将底层 time.Time 作为结构元素处理。
  • 注意DecodeElement返回错误,如果不是nil,应该检查并返回。
  • 出于好奇,使用类型定义而不是嵌入类型有什么缺点吗?即type customTime time.Time
【解决方案2】:

从我阅读的内容来看,encoding/xml 有一些已知问题已被推迟到以后的日期......

要解决这个问题,不要使用time.Time 类型,而是使用string 并在之后处理解析。

我在获取时间时遇到了很多麻烦。解析以使用以下格式的日期:“Fri, 09 Aug 2013 19:39:39 GMT”

奇怪的是,我发现“net/http”有一个 ParseTime 函数,它接受一个完美运行的字符串...... http://golang.org/pkg/net/http/#ParseTime

【讨论】:

  • 最奇怪的是,一旦我将日期字段的类型设置为字符串,一切都开始解析......
【解决方案3】:

我已经实现了一个符合规范的 xml dateTime 格式,你可以在 GitHub 上找到它:https://github.com/datainq/xml-date-time

您可以在 W3C 中找到 XML dateTime spec

【讨论】:

    【解决方案4】:
    const shortForm = "20060102" // yyyymmdd date format
    

    它是不可读的。但它在 Go 中是正确的。可以在http://golang.org/src/time/format.go阅读源码

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多