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

huangapple go评论143阅读模式
英文:

Go: Marshall array/slice of different types to XML

问题

我有一个结构体:

  1. type Response struct {
  2. Verbs []interface{}
  3. }

还有一些其他的动词结构体,比如:

  1. type Verb1 struct {
  2. Field1 string
  3. ...
  4. }
  5. type Verb2 struct {
  6. Field2 int
  7. ...
  8. }

如何从对象

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

生成如下的 XML:

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

我尝试使用 encoding/xml,但它也生成了 Verbs 元素,如下所示:

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

如何避免生成 <Verbs>

英文:

I have a struct

  1. type Response struct {
  2. Verbs []interface{}
  3. }

and some another structs of verbs like

  1. type Verb1 struct{
  2. Field1 string
  3. ...
  4. }
  5. type Verb2 struct{
  6. Field2 int
  7. ...
  8. }

How to from object

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

to get XML like

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

?

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

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

How to avoid generations of <Verbs>?

答案1

得分: 1

你需要明确命名Verb类型。

  1. package main
  2. import (
  3. "encoding/xml"
  4. "fmt"
  5. )
  6. type Root struct {
  7. Container []interface{}
  8. }
  9. type A struct {
  10. XMLName xml.Name `xml:"A"`
  11. Value string `xml:",chardata"`
  12. }
  13. type B struct {
  14. XMLName xml.Name `xml:"B"`
  15. Value string `xml:",chardata"`
  16. }
  17. func main() {
  18. r := Root{
  19. Container: []interface{}{
  20. A{Value: "a"},
  21. B{Value: "b"},
  22. },
  23. }
  24. text, _ := xml.Marshal(r)
  25. fmt.Println(string(text))
  26. }

Playground

英文:

You need to name Verb types explicitly.

  1. package main
  2. import (
  3. "encoding/xml"
  4. "fmt"
  5. )
  6. type Root struct {
  7. Container []interface{}
  8. }
  9. type A struct {
  10. XMLName xml.Name `xml:"A"`
  11. Value string `xml:",chardata"`
  12. }
  13. type B struct {
  14. XMLName xml.Name `xml:"B"`
  15. Value string `xml:",chardata"`
  16. }
  17. func main() {
  18. r := Root{
  19. Container: []interface{}{
  20. A{Value: "a"},
  21. B{Value: "b"},
  22. },
  23. }
  24. text, _ := xml.Marshal(r)
  25. fmt.Println(string(text))
  26. }

<kbd>Playground</kbd>

huangapple
  • 本文由 发表于 2016年3月18日 19:08:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/36082838.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定