Unmarshal Nested xml with Go

£可爱£侵袭症+ 提交于 2019-12-12 09:16:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!