1 回答

TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以簡(jiǎn)單地迭代您的類(lèi)型的節(jié)點(diǎn),并通過(guò)打開(kāi)它們的屬性來(lái)Element創(chuàng)建Apple和結(jié)構(gòu):PeachName
for _, element := range e.Nodes {
switch element.Name {
case "apple":
apples = append(apples, Apple{})
case "peach":
peaches = append(peaches, Peach{})
}
}
另一個(gè)更復(fù)雜的解決方案(但也更優(yōu)雅和實(shí)用)是在您的類(lèi)型上實(shí)現(xiàn)您自己的UnmarshalXML方法,這將直接用正確的類(lèi)型填充它:Element
type Apple struct {
Color string
}
type Peach struct {
Size string
}
type Fruits struct {
Apples []Apple
Peaches []Peach
}
type Element struct {
XMLName xml.Name `xml:"element"`
Nodes []struct {
Name string `xml:"name,attr"`
Apple struct {
Color string `xml:"color"`
} `xml:"apple"`
Peach struct {
Size string `xml:"size"`
} `xml:"peach"`
} `xml:"node"`
}
func (f *Fruits) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
var element Element
d.DecodeElement(&element, &start)
for _, el := range element.Nodes {
switch el.Name {
case "apple":
f.Apples = append(f.Apples, Apple{
Color: el.Apple.Color,
})
case "peach":
f.Peaches = append(f.Peaches, Peach{
Size: el.Peach.Size,
})
}
}
return nil
}
func main() {
f := Fruits{}
err := xml.Unmarshal([]byte(x), &f)
if err != nil {
panic(err)
}
fmt.Println("Apples:", f.Apples)
fmt.Println("Peaches", f.Peaches)
}
這是第二個(gè)解決方案的游樂(lè)場(chǎng)鏈接
結(jié)果:
Apples: [{red}]
Peaches [{medium}]
- 1 回答
- 0 關(guān)注
- 212 瀏覽
添加回答
舉報(bào)