Golang encoding/xml.Decoder.DecodeElement() function example

package encoding/xml

DecodeElement works like xml.Unmarshal except that it takes a pointer to the start XML element to decode into v. It is useful when a client reads some raw XML tokens itself but also wants to defer to Unmarshal for some elements.

Golang encoding/xml.Decoder.DecodeElement() function usage example

 type Rect struct {
 Date string `xml:"data-date,attr"`
 Num  string `xml:"data-count,attr"`
 }

 func (c *Contribution) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
 var i Rect
 err := d.DecodeElement(&i, &start) // <- here
 if err != nil {
 return err
 }

 c.Date, err = time.Parse(dateFormat, i.Date)
 if err != nil {
 return err
 }
 c.Num, err = strconv.Atoi(i.Num)
 if err != nil {
 return err
 }
 return nil
 }

Reference :

http://golang.org/pkg/encoding/xml/#Decoder.DecodeElement

Advertisement