drtppp75155 2016-12-14 13:01
浏览 391
已采纳

从XML解析日期不起作用

If I execute time.Parse() with simple values - then everything is fine, but parsing XML does not.

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

  • 写回答

1条回答 默认 最新

  • download1323 2016-12-14 13:09
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看