date
is an XML attribute, not an element. Therefore, you must implement the xml.UnmarshalerAttr
interface rather than xml.Unmarshaler
:
package main
import (
"encoding/xml"
"fmt"
"time"
)
type xmlSource struct {
XMLName xml.Name `xml:"BicDBList"`
Base string `xml:"Base,attr"`
Items []item `xml:"item"`
}
// Item represent structure of node "item"
type item struct {
File string `xml:"file,attr"`
Date customDate `xml:"date,attr"`
}
type customDate struct {
time.Time
}
func (c *customDate) UnmarshalXMLAttr(attr xml.Attr) error {
loc, err := time.LoadLocation("Europe/Moscow")
if err != nil {
return err
}
prs, err := time.ParseInLocation("02.01.2006", attr.Value, loc)
if err != nil {
return err
}
c.Time = prs
return nil
}
var data = []byte(`<BicDBList Base="/mcirabis/BIK/">
<item file="bik_db_09122016.zip" date="09.12.2016"/>
<item file="bik_db_08122016.zip" date="08.12.2016"/>
<item file="bik_db_07122016.zip" date="07.12.2016"/>
<item file="bik_db_06122016.zip" date="06.12.2016"/>
</BicDBList>`)
func main() {
var sample xmlSource
err := xml.Unmarshal(data, &sample)
if err != nil {
println(err.Error())
}
fmt.Printf("%#v
", sample)
}
https://play.golang.org/p/U56qfEOe-A