Home > Article > Backend Development > How to Parse Custom Time.Time Fields in Go XML?
Custom XML Parsing for Time.Time Fields in Go
When unmarshaling XML data into a Go struct, you may encounter a situation where the date field format differs from the default time.Time format, leading to an unmarshaling error. This question delves into the options available to specify a custom date format during the unmarshaling process.
The issue stems from the fact that time.Time does not implement the xml.Unmarshaler interface, preventing you from specifying a custom date format. As a solution, you can create a wrapper struct with an anonymous time.Time field and implement your own UnmarshalXML method with the desired date format.
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 }
This approach allows you to unmarshal XML documents with custom date formats while maintaining type safety. If the date is stored as an attribute, a similar approach can be used by implementing UnmarshalXMLAttr instead. An example implementation is available at http://play.golang.org/p/EFXZNsjE4a.
The above is the detailed content of How to Parse Custom Time.Time Fields in Go XML?. For more information, please follow other related articles on the PHP Chinese website!