How does a simple xml element unmarshal to a golang struct?

人盡茶涼 提交于 2019-12-02 03:36:22

问题


Assume the following xml element, with an attribute and a floating point value:

<thing prop="1">
  1.23
</thing>
<thing prop="2">
  4.56
</thing>

In order to unmarshal it, how should I define my struct?

type ThingElem struct {
    Prop  int   `xml:"prop,attr"`
    Value float // ???
}

type ThingWrapper struct {
    T ThingElem `xml:"thing"`
}

// VS

type ThingElem struct {
    XMLName xml.Name `xml:"thing"` // Do I even need this?
    Prop    int      `xml:"prop,attr"`
    Value   float    // ???
}

The usage of the XMLName Property confuses me. When should it be placed in the struct, and when in a wrapper as tag?


回答1:


Below you can find the code to unmarshal the given data.

  1. The float values cannot be correctly unmarshalled until you get rid of spaces.
  2. The contents of the tag can be referenced using ",chardata" annotation.
  3. You do not need to specify xml.Name field in structure as long as it is not ambiguous which structure should be used.

package main

import (
    "encoding/xml"
    "fmt"
)

type Root struct {
    Things []Thing `xml:"thing"`
}

type Thing struct {
    Prop  int     `xml:"prop,attr"`
    Value float64 `xml:",chardata"`
}

func main() {
    data := `
<root>
<thing prop="1">1.23</thing>
<thing prop="2">4.56</thing>
</root>
`
    thing := &Root{}
    err := xml.Unmarshal([]byte(data), thing)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(thing)
}


来源:https://stackoverflow.com/questions/26911763/how-does-a-simple-xml-element-unmarshal-to-a-golang-struct

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