3

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.

2 Answers 2

3

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

1
  • Thank you so much! And thanks for pointing to other mistakes. Commented May 29, 2016 at 21:29
2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.