猿问

如果 xml.Marshal 为空,则忽略结构

我需要输出一个 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>标签在那里,我怎样才能摆脱它?


明月笑刀无情
浏览 117回答 1
1回答

繁星淼淼

您有一些语法错误,但可以将 child 设置为指针:type Parent struct {&nbsp; &nbsp; XMLName xml.Name `xml:"parent"`&nbsp; &nbsp; Name&nbsp; &nbsp; string&nbsp; &nbsp;`xml:"name,omitempty"`&nbsp; &nbsp; Age&nbsp; &nbsp; &nbsp;int64&nbsp; &nbsp; `xml:"age,omitempty"`&nbsp; &nbsp; Child&nbsp; &nbsp;*Child&nbsp; &nbsp; `xml:"child,omitempty"`}当它为零时,它将是空的。工作演示
随时随地看视频慕课网APP

相关分类

Go
我要回答