简体   繁体   中英

Unmarshall XML to embedded struct in go

I have a flat XML structure, which I want to unmarshall in to a struct which has one part embedded. Is this possible? What is the syntax, or what custom method can I write?

In this example, I tag the nested struct with a guess: xml:"" , which is skipped over by "encoding/xml".

type FloatHolder struct {
    Value float32    `xml:"value"`
}


type pv struct {
    XMLName    xml.Name  `xml:"series"`
    Test1 FloatHolder `xml:""`   // does not populate :-(
    Test2 FloatHolder `xml:"nested"` // populates
}
func main() {
    contents := `<series>
                   <nested>
                     <value>1234</value>
                   </nested>
                   <value>1234</value>
                 </series>`

    m := &pv{}

    err := xml.Unmarshal([]byte(contents), &m)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%f %f\n", m.Test1.Value, m.Test2.Value)
}

Output: "0.000000 1234.000000"

Playground: https://play.golang.org/p/aEdDLFYqL5

Thanks!

EDIT: After comment interaction.

Yes you can. Let's say

XML:

<series>
    <value>123456</value>
</series>

Struct definition:

type FloatHolder struct {
    Value float32 `xml:",chardata"`
}

type pv struct {
    XMLName xml.Name    `xml:"series"`
    Test2   FloatHolder `xml:"value"`
}

Go Playground link: https://play.golang.org/p/9sWQaw0HlS


Actually it's not a nested field, as per your XML. It belongs to series element.

Update your struct to following:

type pv struct {
    XMLName xml.Name    `xml:"series"`
    Test1   float32     `xml:"value"`
    Test2   FloatHolder `xml:"nested"`
}

Go Playground Link: https://play.golang.org/p/-mWrUMJXxX

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM