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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作