Go unmarshall XML
我目前有以下XMLGo unmarshall XML,xml,go,Xml,Go,我目前有以下XML <monster name="Valkyrie" nameDescription="a valkyrie" race="blood" experience="85" speed="190" manacost="450"> <health now="190" max="190" /> <look type="139" head="113" body="57" legs="95" feet="113" corpse="20523" /
<monster name="Valkyrie" nameDescription="a valkyrie" race="blood" experience="85" speed="190" manacost="450">
<health now="190" max="190" />
<look type="139" head="113" body="57" legs="95" feet="113" corpse="20523" />
<voices interval="5000" chance="10">
<voice sentence="Another head for me!" />
<voice sentence="Head off!" />
<voice sentence="Your head will be mine!" />
<voice sentence="Stand still!" />
<voice sentence="One more head for me!" />
</voices>
</monster>
但是我不知道如何读取voices元素,只要使用
xml.Unmarshal(xmlString,data)
下面是xml解组的完整示例只需使用
xml.Unmarshal(xmlString,data)
下面是xml解组的完整示例您刚刚错过了为
语音指定xml元素映射的步骤
:
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)
}
更好的方法是,放下monsterVoice,像这样使用子选择器:
type monster struct {
XMLName xml.Name `xml:"monster"`
....
Voices []monsterSentence `xml:"voices>voice"`
}
然后我们就可以摆脱上一个演示中尴尬的结果.Voices.Voices
:
for _, r := range result.Voices {
fmt.Println(r.Sentence)
}
输出:(两个演示产生相同的输出)
您刚刚错过了为
语音
指定XML元素映射:
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)
}
更好的方法是,放下monsterVoice,像这样使用子选择器:
type monster struct {
XMLName xml.Name `xml:"monster"`
....
Voices []monsterSentence `xml:"voices>voice"`
}
然后我们就可以摆脱上一个演示中尴尬的结果.Voices.Voices
:
for _, r := range result.Voices {
fmt.Println(r.Sentence)
}
输出:(两个演示产生相同的输出)