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

标签 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没有定义 child ,然后将其编码到 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>是空的在那里标记,我怎样才能摆脱它?

最佳答案

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

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

为nil时为空

Working Demo

关于如果 xml.Marshal 为空,则忽略结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56348296/

相关文章:

go - vscode 不检测错误 golang

Java DOM 解析器 XML

java - 无法使用 XSLT 1.0 更新 XML 节点属性

http.ListenAndServe 仅适用于本地主机?

Go get path 是 GOROOT,而不是 GOPATH 错误,即使在 Windows 中设置了 env

go - 使用空接口(interface)或空结构作为映射的值有什么区别?

python - 使用 Python 编辑 XML 文件内容

python - 如何保持 numpy 数组的精度

xml - 错误 #2044 : Unhandled securityError:. 文本=错误 #2048:违反安全沙箱:

go - 从字符串中提取冒号分隔的值