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

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

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))
}

Playground

英文:

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))
}

<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:

确定