Marshalling XML in GOlang: field is empty (APPEND doesn't work?)

前端 未结 2 777
深忆病人
深忆病人 2021-01-20 14:44

i\'m learning to create XML in Go. Here\'s my code:

type Request struct {
    XMLName       xml.Name        `xml:\"request\"`
    Action        string                


        
相关标签:
2条回答
  • 2021-01-20 14:56

    The members that you want to marshal have to be exported (capitalized). Try:

    type point struct {
        Geo    string `xml:"point"`
        Radius int    `xml:"radius,attr"`
    }
    

    From the encoding/xml doc:

    The XML element for a struct contains marshalled elements for each of the exported fields of the struct.

    [..]

    Because Unmarshal uses the reflect package, it can only assign to exported (upper case) fields.

    0 讨论(0)
  • 2021-01-20 15:15

    Several things are wrong in your code. When working with encoding packages in Go, all the fields you want to marshal/unmarshal have to be exported. Note that the structs themselves do not have to be exported.

    So, first step is to change the point struct to export the fields:

    type point struct {
        Geo    string `xml:"point"`
        Radius int    `xml:"radius,attr"`
    }
    

    Now, if you want to display the Geo field inside a point, you have to add ,cdata to the xml tag. Finally, there is no need to add an omitempty keyword to a slice.

    type Request struct {
        XMLName xml.Name `xml:"request"`
        Action  string   `xml:"action,attr"`
        Point   []point  `xml:"point"`
    }
    
    type point struct {
        Geo    string `xml:",chardata"`
        Radius int    `xml:"radius,attr"`
    }
    

    Go playground

    0 讨论(0)
提交回复
热议问题