如果为空,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) )

}

富输出:


<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 中的示例适用于隐藏空父级,但填充它使它变得更加困难。“ panic: runtime error: invalid memory address or nil pointer dereference”


胡说叔叔
浏览 190回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go