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 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题