dongyi3616 2019-05-28 18:39
浏览 74
已采纳

xml.Marshal如果为空则忽略struct

I need to output an XML file, and I've constructed a few structs that represent it As a basic example, say this:

type Parent struct {
    XMLName xml.Name `xml:"parent"`
    Name    string   `xml:"name,omitempty"`
    Age     int64    `xml:"age,omitempty"`
    Child   Child    `xml:"child,omitempty`
}

type Child struct {
    XMLName  xml.Name `xml:"child,omitempty"`
    Name     string   `xml:"name,omitempty"`
    Gender   string   `xml:"gender,omitempty"`
    Thoughts string   `xml:",innerxml,omitempty"`
}

I expect that when I create a Parent without defining the child, and then marshal it into an XML file...

parent := Parent{
    Name: "Beatrice",
    Age: "23",
}
_ = xml.MarshalIndent(parent, "", "    ")

...that I should get an XML file not containing a child tag:

<parent>
    <name>Beatrice</name>
    <age>23</age>
</parent>

Instead, I get this:

<parent>
    <name>Beatrice</name>
    <age>23</age>
    <child></child>
</parent>

Why is the empty <child></child> tag there, and how can I get rid of it?

  • 写回答

1条回答 默认 最新

  • dongqiang5541 2019-05-28 18:45
    关注

    You have a few syntax errors but you can set child as a pointer:

    type Parent struct {
        XMLName xml.Name `xml:"parent"`
        Name    string   `xml:"name,omitempty"`
        Age     int64    `xml:"age,omitempty"`
        Child   *Child    `xml:"child,omitempty"`
    }
    

    When it's nil, it will be empty.

    Working Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Jenkins+k8s部署slave节点offline
  • ¥15 微信小游戏反编译后,出现找不到分包的情况
  • ¥15 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题