如何在Go中使用可选标签封送XML

The code for my problem is here: https://play.golang.org/p/X8Ey2hqmxL

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(&fr, "", "\t")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(xmlBlob))
}

I need to marshall data into SOAP xml. I'm currently getting this result:

<Carriage>
    <mainCarriage loadFactor="70" seaCargoType="Container">
        <sea xmlns="http://www.example.com/XMLSchema/standard/2012"></sea>
    </mainCarriage>
</Carriage>

But I need this result:

<Carriage>
    <mainCarriage>
        <sea xmlns="http://www.example.com/XMLSchema/standard/2012" loadFactor="70" seaCargoType="Container"></sea>
    </mainCarriage>
</Carriage>

No matter what I try I cannot marshal the structs so that the loadFactor and the seaCargoType are attrs of the sea tag.

The Carriage struct takes an empty interface because depending on the shipment type the tag should be either sea or road but never both.

Put >. after mainCarriage field tag to indicate that you want to put contents of the field inside mainCarriage tag. Change the name of Sea field to XMLName as required by marshaller.

package main

import (
    "encoding/xml"
    "fmt"
    "log"
)

type Carriage struct {
    MainCarriage interface{} `xml:"mainCarriage>."`
}

type SeaCarriage struct {
    XMLName      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(&fr, "", "\t")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(xmlBlob))
}

Playground