如果为空,Golang隐藏XML父标记

经过一些追踪和错误,我想分享我正在处理的问题.

我正在填充结构并将其转换为XML(xml.Marshal)
如下所示,Foo示例按预期工作.但是Bar示例创建了一个空group1.

所以我的问题是:“如果没有设置子代,我如何防止生成Group1.”

package main

import (
    "fmt"
    "encoding/xml"
)

type Example1 struct{
    XMLName  xml.Name `xml:"Example1"`
    Element1 string   `xml:"Group1>Element1,omitempty"`
    Element2 string   `xml:"Group1>Element2,omitempty"`
    Element3 string   `xml:"Group2>Example3,omitempty"`
}

func main() {
    foo := &Example1{}
    foo.Element1 = "Value1" 
    foo.Element2 = "Value2" 
    foo.Element3 = "Value3" 

    fooOut,_ := xml.Marshal(foo)
    fmt.Println( string(fooOut) )

    bar  := &Example1{}
    bar.Element3 = "Value3"
    barOut,_ := xml.Marshal(bar)
    fmt.Println( string(barOut) )
}

Foo输出

<Example1>
    <Group1>
        <Element1>Value1</Element1>
        <Element2>Value2</Element2>
    </Group1>
    <Group2>
        <Example3>Value3</Example3>
    </Group2>
</Example1>

条形输出

<Example1>
    <Group1></Group1>  <------ How to remove the empty parent value ? 
    <Group2>
        <Example3>Value3</Example3>
    </Group2>
</Example1>

加成

此外,我已尝试执行以下操作,但仍生成一个空的“Group1”:

type Example2 struct{
    XMLName  xml.Name `xml:"Example2"`
    Group1   struct{
        XMLName  xml.Name `xml:"Group1,omitempty"`
        Element1 string   `xml:"Element1,omitempty"`
        Element2 string   `xml:"Element2,omitempty"`
    }
    Element3 string   `xml:"Group2>Example3,omitempty"`
}

完整代码可在此处找到:http://play.golang.org/p/SHIcBHoLCG.例子来

编辑:更改了golang示例以使用MarshalIndent提高可读性

编辑2 Ainar-G Works的例子很适合隐藏空父,但填充它会让它变得更难. “恐慌:运行时错误:无效的内存地址或无指针取消引用”

Example1不起作用,因为omitempty标签显然只适用于元素本身,而不适用于a> b> c封闭元素.

Example2不起作用,因为omitempty不会将空结构识别为空. From the doc

The empty values are false,any nil pointer or interface value,and any array,slice,map,or string of length zero.

没有提到结构.您可以通过将Group1更改为指向结构的指针来使baz示例工作:

type Example2 struct {
    XMLName  xml.Name `xml:"Example1"`
    Group1   *Group1
    Element3 string `xml:"Group2>Example3,omitempty"`
}

type Group1 struct {
    XMLName  xml.Name `xml:"Group1,omitempty"`
    Element1 string   `xml:"Element1,omitempty"`
    Element2 string   `xml:"Element2,omitempty"`
}

然后,如果要填充Group1,则需要单独分配:

foo.Group1 = &Group1{
    Element1: "Value1",}

示例:http://play.golang.org/p/mgpI4OsHf7

相关文章

什么是Go的接口? 接口可以说是一种类型,可以粗略的理解为他...
1、Golang指针 在介绍Golang指针隐式间接引用前,先简单说下...
1、概述 1.1&#160;Protocol buffers定义 Protocol buffe...
判断文件是否存在,需要用到"os"包中的两个函数: os.Stat(...
1、编译环境 OS :Loongnix-Server Linux release 8.3 CPU指...
1、概述 Golang是一种强类型语言,虽然在代码中经常看到i:=1...