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

我的问题的代码在这里: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 结构采用空接口,因为根据运输类型,标签应该是海运或公路,但不能同时是两者。


慕姐8265434
浏览 162回答 1
1回答

森栏

把>.后mainCarriage场的标签,以表明你希望把字段的内容里面mainCarriage的标签。将Sea字段名称更改XMLName为 marshaller 的要求。package mainimport (&nbsp; &nbsp; "encoding/xml"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "log")type Carriage struct {&nbsp; &nbsp; MainCarriage interface{} `xml:"mainCarriage>."`}type SeaCarriage struct {&nbsp; &nbsp; XMLName&nbsp; &nbsp; &nbsp; xml.Name `xml:"http://www.example.com/XMLSchema/standard/2012 sea"`&nbsp; &nbsp; LoadFactor&nbsp; &nbsp;float64&nbsp; `xml:"loadFactor,attr"`&nbsp; &nbsp; SeaCargoType string&nbsp; &nbsp;`xml:"seaCargoType,attr"`}type RoadCarriage struct {&nbsp; &nbsp; Road xml.Name `xml:"http://www.example.com/XMLSchema/standard/2012 road"`}func main() {&nbsp; &nbsp; fr := Carriage{&nbsp; &nbsp; &nbsp; &nbsp; MainCarriage: SeaCarriage{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; LoadFactor:&nbsp; &nbsp;70,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SeaCargoType: "Container",&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; }&nbsp; &nbsp; xmlBlob, err := xml.MarshalIndent(&fr, "", "\t")&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatal(err)&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(string(xmlBlob))}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go