Вы можете просто перебирать узлы вашего типа Element
и создавать структуры Apple
и Peach
по мере необходимости, включив их атрибут Name
:
for _, element := range e.Nodes {
switch element.Name {
case "apple":
apples = append(apples, Apple{})
case "peach":
peaches = append(peaches, Peach{})
}
}
Вот ссылка на игровую площадку .
Другое, более сложное решение (но также более изящное и практичное) было бы реализовать собственный метод UnmarshalXML
для типа 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)
}
Вот ссылка на игровую площадку для этого второго решения
Результат:
Apples: [{red}]
Peaches [{medium}]