Reputation: 180
i'm learning to create XML in Go. Here's my code:
type Request struct {
XMLName xml.Name `xml:"request"`
Action string `xml:"action,attr"`
...
Point []point `xml:"point,omitempty"`
}
type point struct {
geo string `xml:"point"`
radius int `xml:"radius,attr"`
}
func main() {
v := &Request{Action: "get-objects"}
v.Point = append(v.Point, point{geo: "55.703038, 37.554457", radius: 10})
output, err := xml.MarshalIndent(v, " ", " ")
if err != nil {
fmt.Println("error: %v\n", err)
}
os.Stdout.Write([]byte(xml.Header))
os.Stdout.Write(output)
}
I expect the output to be like:
<?xml version="1.0" encoding="UTF-8"?>
<request action="get-objects">
<point radius=10>55.703038, 37.554457</point>
</request>
But what I'm getting is:
<?xml version="1.0" encoding="UTF-8"?>
<request action="get-objects">
<point></point>
</request>
What am I missing or doing wrong? Because the "name,attr" thing works perfect for everything else (for example, for the "request" field, as you can see). Thanks.
Upvotes: 3
Views: 1409
Reputation: 12246
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"`
}
Upvotes: 3
Reputation: 182659
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.
Upvotes: 2