title: How to marshal xml with optional tags in Go
body: <p>The code for my problem is here: <a href="https://play.golang.org/p/X8Ey2hqmxL" rel="nofollow">https://play.golang.org/p/X8Ey2hqmxL</a></p>
  
  <pre><code>package main
  
  import (
      "encoding/xml"
      "fmt"
      "log"
  )
  
  type Carriage struct {
      MainCarriage interface{} `xml:"mainCarriage"`
  }
  
  type SeaCarriage struct {
      Sea          xml.Name `xml:"http://www.example.com/XMLSchema/standard/2012 sea"`
      LoadFactor   float64  `xml:"loadFactor,attr"`
      SeaCargoType string   `xml:"seaCargoType,attr"`
  }
  
  type RoadCarriage struct {
      Road xml.Name `xml:"http://www.example.com/XMLSchema/standard/2012 road"`
  }
  
  func main() {
  
      fr := Carriage{
          MainCarriage: SeaCarriage{
              LoadFactor:   70,
              SeaCargoType: "Container",
          },
      }
      xmlBlob, err := xml.MarshalIndent(&amp;fr, "", "\t")
      if err != nil {
          log.Fatal(err)
      }
      fmt.Println(string(xmlBlob))
  }
  </code></pre>
  
  <p>I need to marshall data into SOAP xml. I'm currently getting this result:</p>
  
  <pre><code>&lt;Carriage&gt;
      &lt;mainCarriage loadFactor="70" seaCargoType="Container"&gt;
          &lt;sea xmlns="http://www.example.com/XMLSchema/standard/2012"&gt;&lt;/sea&gt;
      &lt;/mainCarriage&gt;
  &lt;/Carriage&gt;
  </code></pre>
  
  <p>But I need this result:</p>
  
  <pre><code>&lt;Carriage&gt;
      &lt;mainCarriage&gt;
          &lt;sea xmlns="http://www.example.com/XMLSchema/standard/2012" loadFactor="70" seaCargoType="Container"&gt;&lt;/sea&gt;
      &lt;/mainCarriage&gt;
  &lt;/Carriage&gt;
  </code></pre>
  
  <p>No matter what I try I cannot marshal the structs so that the loadFactor and the seaCargoType are attrs of the <code>sea</code> tag.</p>
  
  <p>The Carriage struct takes an empty interface because depending on the shipment type the tag should be either sea or road but never both.</p>