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

I have a struct

type Response struct {
  Verbs []interface{}
}

and some another structs of verbs like

type Verb1 struct{
  Field1 string
  ...
}

type Verb2 struct{
  Field2 int
  ...
} 

How to from object

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

to get XML like

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

?

I tried to use encoding/xml but it generates element Verbs too like

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

How to avoid generations of <Verbs>?

You need to name Verb types explicitly.

package main

import (
    "encoding/xml"
    "fmt"
)

type Root struct {
    Container []interface{}
}

type A struct {
    XMLName xml.Name `xml:"A"`
    Value   string   `xml:",chardata"`
}

type B struct {
    XMLName xml.Name `xml:"B"`
    Value   string   `xml:",chardata"`
}

func main() {
    r := Root{
        Container: []interface{}{
            A{Value: "a"},
            B{Value: "b"},
        },
    }
    text, _ := xml.Marshal(r)
    fmt.Println(string(text))
}

Playground