如果为空,Golang隐藏XML父标记
经过一些追踪和错误,我想分享我正在处理的问题.
我正在填充结构并将其转换为XML(xml.Marshal) 所以我的问题是:“如果没有设置子代,我如何防止生成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:
没有提到结构.您可以通过将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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |