3

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 
2
  • 2
    I don't see a question here.... Commented Nov 6, 2015 at 0:31
  • You're ignoring the error from unmarshal, you're trying to unmarshal a date into an int, and the datevalues field isn't exported so it's not seen by the xml package. Commented Nov 6, 2015 at 1:21

1 Answer 1

12

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the response. I didn't realize that the fields within the struct had to be exported in order to work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.