doudu9094 2016-05-28 23:05
浏览 48
已采纳

在GOlang中将XML编组:字段为空(APPEND不起作用?)

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
", 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条回答 默认 最新

  • dongxing8766 2016-05-29 09:18
    关注

    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条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?