How do we dynamically unmarshal child XML with attributes from parent?
We have the the following XMLs:
<!-- Report I -->
<report type="YYYY-MM-DD">
<created_at>2016-01-01</created_at>
</report>
<!-- Report II -->
<report type="DD-MM-YYYY">
<created_at>01-01-2016</created_at>
</report>
And we have the following structure:
type Report struct {
XMLName xml.Name `xml:"report"`
Type string `xml:"type,attr"`
CreatedAt *ReportDate `xml:"created_at"`
}
type ReportDate struct {
time.Time
}
func (c *ReportDate) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
const format = "02-01-2006" // or "2016-01-02" depending on parent's "type"
var v string
d.DecodeElement(&v, &start)
parse, err := time.Parse(format, v)
if err != nil {
return err
}
*c = ReportDate{parse}
return nil
}
Will it be possible for ReportDate
to obtain type="?"
from it's parent in UnmarshalXML
? Or will it be possible for Report
to pass down attribute values to all child tags? If it is possible, how do we accomplish this?