title: Golang Hide XML parent tag if empty
body: <p>After some trail and error I'd like to share the issue I am dealing with. </p>
  
  <p>I'm populating an struct and convert it to an XML ( xml.Marshal ) 
  As you can see below the Foo example works as expected. The Bar example however creates an empty group1. </p>
  
  <p>So my question is : "How do I prevent Group1 to be generated if there are no children set." </p>
  
  <pre><code>package main
  
  import (
      "fmt"
      "encoding/xml"
  )
  
  type Example1 struct{
      XMLName  xml.Name `xml:"Example1"`
      Element1 string   `xml:"Group1&gt;Element1,omitempty"`
      Element2 string   `xml:"Group1&gt;Element2,omitempty"`
      Element3 string   `xml:"Group2&gt;Example3,omitempty"`
  }
  
  func main() {
      foo := &amp;Example1{}
      foo.Element1 = "Value1" 
      foo.Element2 = "Value2" 
      foo.Element3 = "Value3" 
  
      fooOut, _ := xml.Marshal(foo)
      fmt.Println( string(fooOut) )
  
      bar  := &amp;Example1{}
      bar.Element3 = "Value3"
      barOut, _ := xml.Marshal(bar)
      fmt.Println( string(barOut) )
  }
  </code></pre>
  
  <p>Foo Output : </p>
  
  <pre><code>&lt;Example1&gt;
      &lt;Group1&gt;
          &lt;Element1&gt;Value1&lt;/Element1&gt;
          &lt;Element2&gt;Value2&lt;/Element2&gt;
      &lt;/Group1&gt;
      &lt;Group2&gt;
          &lt;Example3&gt;Value3&lt;/Example3&gt;
      &lt;/Group2&gt;
  &lt;/Example1&gt;
  </code></pre>
  
  <p>Bar Output : </p>
  
  <pre><code>&lt;Example1&gt;
      &lt;Group1&gt;&lt;/Group1&gt;  &lt;------ How to remove the empty parent value ? 
      &lt;Group2&gt;
          &lt;Example3&gt;Value3&lt;/Example3&gt;
      &lt;/Group2&gt;
  &lt;/Example1&gt;
  </code></pre>
  
  <p><strong>Addition</strong></p>
  
  <p>Additionally i have tried doing the following, but still generates an empty "Group1": </p>
  
  <pre><code>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&gt;Example3,omitempty"`
  }
  </code></pre>
  
  <p>The full code can be found here : <a href="http://play.golang.org/p/SHIcBHoLCG" rel="noreferrer">http://play.golang.org/p/SHIcBHoLCG</a> . example to </p>
  
  <p><strong>EDIT</strong> : Changed the golang example to use MarshalIndent for readability</p>
  
  <p><strong>Edit 2</strong> The example from Ainar-G Works good for hiding the empty parent, but Populating it makes it a lot harder.  "<code>panic: runtime error: invalid memory address or nil pointer dereference</code>"</p>