I have the following snippet of code that I have been banging my head on the wall trying to make it work. I have searched everywhere for a solution, but none of the ones that I have found seem to work.
It seems that I have an issue with my mapping for the xml.Unmarshal
command as it pertains to nested fields. The code below works for retrieving the first value which is called unit
, and is on the top level of the xml code.
The other two fields come up as zero, and they are nested two level deep. That implies that the structure isn't set up correctly. Here is the code.
package main
import (
"encoding/xml"
"fmt"
)
type datevalue struct {
Date int `xml:"date"`
Value float32 `xml:"value"`
}
type pv struct {
XMLName xml.Name `xml:"series"`
Unit string `xml:"unit"`
datevalues datevalue `xml:"values>dateValue"`
}
func main() {
contents := `<series>
<timeUnit>DAY</timeUnit>
<unit>Wh</unit><measuredBy>INVERTER</measuredBy>
<values><dateValue>
<date>2015-11-04 00:00:00</date>
<value>5935.405</value>
</dateValue></values>
</series>`
m := &pv{}
xml.Unmarshal([]byte(contents), &m)
fmt.Printf("%s %f %d\n", m.Unit, m.datevalues.Value, m.datevalues.Date)
}
And here is the output:
Wh 0.000000 0
datevalues
field isn't exported so it's not seen by the xml package.