Go:将不同类型的 Marshall 数组/切片转换为 XML

我有一个结构


type Response struct {

  Verbs []interface{}

}

以及其他一些动词结构,如


type Verb1 struct{

  Field1 string

  ...

}


type Verb2 struct{

  Field2 int

  ...

如何从对象


&Response{Verbs: []interface{}{Verb1{}, Verb2{}, Verb1{}}}

获取 XML 之类的


<Response><Verb1>...</Verb1><Verb2>...</Verb2><Verb1>...</Verb1></Response>

?


我尝试使用encoding/xml但它生成元素Verbs太像


<Response><Verbs><Verb1>...</Verb1><Verb2>...</Verb2><Verb1>...</Verb1></Verbs></Response>

如何避免世代相传<Verbs>?


慕尼黑8549860
浏览 143回答 1
1回答

慕村9548890

您需要Verb明确命名类型。package mainimport (&nbsp; &nbsp; "encoding/xml"&nbsp; &nbsp; "fmt")type Root struct {&nbsp; &nbsp; Container []interface{}}type A struct {&nbsp; &nbsp; XMLName xml.Name `xml:"A"`&nbsp; &nbsp; Value&nbsp; &nbsp;string&nbsp; &nbsp;`xml:",chardata"`}type B struct {&nbsp; &nbsp; XMLName xml.Name `xml:"B"`&nbsp; &nbsp; Value&nbsp; &nbsp;string&nbsp; &nbsp;`xml:",chardata"`}func main() {&nbsp; &nbsp; r := Root{&nbsp; &nbsp; &nbsp; &nbsp; Container: []interface{}{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; A{Value: "a"},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; B{Value: "b"},&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; }&nbsp; &nbsp; text, _ := xml.Marshal(r)&nbsp; &nbsp; fmt.Println(string(text))}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go