1 回答

TA貢獻1860條經驗 獲得超8個贊
您可以簡單地迭代您的類型的節點,并通過打開它們的屬性來Element創建Apple和結構:PeachName
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}]
- 1 回答
- 0 關注
- 214 瀏覽
添加回答
舉報