Golang Hide parent XML tag if empty

After some trail and error, I would like to share the issue I'm dealing with.

I fill out the structure and convert it to XML (xml.Marshal) As you can see below, the Foo example works as expected. However, the Bar example creates an empty group1.

So my question is: "How to prevent the gathering of Group1 if there are no children?"

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) ) } 

Output Foo:

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

Bar Out:

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

Adding

In addition, I tried to do the following, but still generates an empty "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"` } 

The full code can be found here: http://play.golang.org/p/SHIcBHoLCG . example

EDIT : modified golang example to use MarshalIndent for readability

Change 2 . The example from Ainar-G Works is good for hiding an empty parent, but populating it makes it a lot more complicated. " panic: runtime error: invalid memory address or nil pointer dereference "

+7
xml go marshalling
source share
1 answer

Example1 does not work, because, apparently, the ,omitempty tag only works with the element itself, and not with the elements a>b>c .

Example2 does not work, because ,omitempty does not recognize empty structures as empty. From the doc :

Null values: false, 0, any nil value or interface value, as well as any array, slice, map, or zero-length string.

No mention of structures. You can create a baz example by changing Group1 to a pointer to a structure:

 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"` } 

Then, if you want to populate Group1 , you need to select it separately:

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

Example: http://play.golang.org/p/mgpI4OsHf7

+11
source share

All Articles