英文:
Go: Marshall array/slice of different types to 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>
?
英文:
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>
?
答案1
得分: 1
你需要明确命名Verb
类型。
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))
}
英文:
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))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论