如何使用Go中的可选标签封送xml

时间:2015-12-11 10:32:19

标签: xml go

我的问题的代码在这里: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))
}

我需要将数据编组到SOAP xml中。我目前得到的结果是:

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

但我需要这个结果:

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

无论我尝试什么,我都无法编组结构,以便loadFactor和seaCargoType成为sea标签的附件。

Carriage结构采用空接口,因为根据货运类型,标签应该是海运或公路,但不能同时使用。

1 个答案:

答案 0 :(得分:2)

>.字段标记后面加mainCarriage表示您要将字段内容放在mainCarriage标记内。根据marshaller的要求,将Sea字段的名称更改为XMLName

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