2 回答
TA贡献1848条经验 获得超6个赞
您刚刚错过了为以下内容指定 XML 元素映射Voices:
type monsterVoice struct {
Voices []monsterSentence `xml:"voice"`
}
在那个小小的添加之后,像往常一样解组应该可以工作:
var result monster
err := xml.Unmarshal([]byte(your_xml_data_string), &result)
if err != nil {
fmt.Println(err)
}
for _, r := range result.Voices.Voices {
fmt.Println(r.Sentence)
}
playground demo 1
更好的是,monsterVoice像这样删除并使用子选择器:
type monster struct {
XMLName xml.Name `xml:"monster"`
....
Voices []monsterSentence `xml:"voices>voice"`
}
那么我们就可以摆脱result.Voices.Voices之前demo中的尴尬了:
for _, r := range result.Voices {
fmt.Println(r.Sentence)
}
playground demo 2
输出:(两个演示产生相同的输出)
Another head for me!
Head off!
Your head will be mine!
Stand still!
One more head for me!
TA贡献1807条经验 获得超9个赞
只需使用 xml.Unmarshal(xmlString, data)
这是 xml 解组的完整示例https://golang.org/src/encoding/xml/example_test.go
- 2 回答
- 0 关注
- 169 浏览
添加回答
举报