xml.Marshal如果为空则忽略struct

时间:2019-05-28 18:39:55

标签: xml go

我需要输出一个XML文件,并且已经构造了一些表示它的结构。作为一个基本示例,请说以下话:

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"`
}

我希望在创建Parent而不定义子级时,然后将其编组为XML文件...

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

...我应该得到一个不包含child标签的XML文件:

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

相反,我得到了:

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

为什么那里有空的<child></child>标签,我该如何摆脱它?

1 个答案:

答案 0 :(得分:3)

您有一些语法错误,但是可以将child设置为指针:

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

为零时,它将为空。

Working Demo