尝试使用Golang encoding/xml将一个结构编码为xml——一个具有交替重复模式的结构



我正在尝试使用encoding/xml包创建一个具有以下顺序的xml文件,并且我已经为静态子元素和转换子元素定义了结构,现在的问题是,我需要以重复的格式保存它,所以我创建了另一个结构来保存静态结构和转换结构的切片,但结果是静态元素都出现在转换元素之前,但我需要它们按顺序交替。这就是我想要的结构:

<background>
//...
<static>
<duration></duration>
<file></file>
</static>
<transition>
<duration>
<from></from>
<to></to>
</transition>
<static>
<duration></duration>
<file></file>
</static>
<transition>
<duration>
<from></from>
<to></to>
</transition>
//...
</background>

但这就是我得到的:

<background>
//...
<static>
<duration></duration>
<file></file>
</static>
<static>
<duration></duration>
<file></file>
</static>
<transition>
<duration>
<from></from>
<to></to>
</transition>
<transition>
<duration>
<from></from>
<to></to>
</transition>
//...
</background>

关于我该怎么做的任何帮助。这些是我创建的结构:

type Static struct {
Duration int    `xml:"duration"`
File     string `xml:"file"`
}
type Transition struct {
Duration float64 `xml:"duration"`
From     string  `xml:"from"`
To       string  `xml:"to"`
}
type ST struct {
Static     []Static     `xml:"static"`
Transition []Transition `xml:"transition"`
}
type Background struct {
XMLName   xml.Name  `xml:"background"`
Comment   string    `xml:",comment"`
ST
}

type Static struct {
XMLName  string `xml:"static"`
Duration int    `xml:"duration"`
File     string `xml:"file"`
}
type Transition struct {
XMLName  string  `xml:"transition"`
Duration float64 `xml:"duration"`
From     string  `xml:"from"`
To       string  `xml:"to"`
}
type Background struct {
XMLName string `xml:"background"`
Items   []interface{}
}
bk := Background{
Items: []interface{}{
&Static{
Duration: 11,
File:     "foo",
},
&Transition{
Duration: 22,
From:     "aaa",
To:       "bbb",
},
&Static{
Duration: 33,
File:     "bar",
},
&Transition{
Duration: 44,
From:     "xxx",
To:       "yyy",
},
},
}
out, err := xml.Marshal(&bk)

应该盖上你的(操场(。

请注意,为了获得一个正确的序列化元素列表(按照指定的顺序依次排列(,您必须使用反映这一点的数据结构;Go切片最适合这种简单的情况。

在复杂的情况下,可以让您的自定义类型实现encoding/xml.Marshaler接口,并使用较低级别的encoding/xml设施以您希望的任何顺序对各个校准器进行编码。

相关内容

最新更新