2016-12-14 53 views
2

如果我用简单的值执行time.Parse() - 那么一切都很好,但解析XML不会。从XML解析日期不起作用

type customDate struct { 
    time.Time 
} 


func (c *customDate) UnmarshalXml(d *xml.Decoder, start xml.StartElement) error { 
    var v string 
    if err := d.DecodeElement(&v, &start); err != nil{ 
     return err 
    } 

    loc, _ := time.LoadLocation("Europe/Moscow") 
    prs, err := time.ParseInLocation("02.01.2006", v, loc) 
    if err != nil { 
     return err 
    } 

    *c = customDate{prs} 
    return nil 
} 

example on playground

回答

2

date是一个XML属性,而不是元件。因此,你必须实现xml.UnmarshalerAttr接口,而不是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\n", sample) 
} 

https://play.golang.org/p/U56qfEOe-A

+0

感谢++++++++ – user2782106