问题
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
回答1:
First of all your code doesn't work because you should use exported fields for marshalling/unmarshalling (see https://golang.org/pkg/encoding/xml/).
You should use
type pv struct {
XMLName xml.Name `xml:"series"`
Unit string `xml:"unit"`
Datevalues datevalue `xml:"values>dateValue"`
}
instead of
type pv struct {
XMLName xml.Name `xml:"series"`
Unit string `xml:"unit"`
datevalues datevalue `xml:"values>dateValue"`
}
Look at DateValues field name. If first symbol is uppercased it's will be exported. Otherwise that field will be ignored while Unmarshal
Second:
After it I noticed that you are ignoring your errors. Please don't ignore them, they are critically useful.
Check it out on the go playgroung
As you can see you use int
datatype for Date
field of datatype
.
If you change type to string
, your code will work.
Third:
I think you really want to unmarshall your date
value into time.Time
.
To do so you can check this related question
The complete working code you can try on the go playground
来源:https://stackoverflow.com/questions/33557401/unmarshal-nested-xml-with-go