gpt4 book ai didi

xml - 解码 XML

转载 作者:数据小太阳 更新时间:2023-10-29 03:06:05 24 4
gpt4 key购买 nike

我目前有以下 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" />
<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>

我正在使用以下结构阅读它

type monster struct {
XMLName xml.Name `xml:"monster"`
Name string `xml:"name,attr"`
NameDescription string `xml:"nameDescription,attr"`
Race string `xml:"race,attr"`
Experience int `xml:"experience,attr"`
Speed int `xml:"speed,attr"`
ManaCost int `xml:"manacost,attr"`
Health monsterHealth `xml:"health"`
Look monsterLook `xml:"look"`
Voices monsterVoice `xml:"voices"`
}

type monsterVoice struct {
Voices []monsterSentence
}

type monsterSentence struct {
XMLName xml.Name `xml:"voice"`
Sentence string `xml:"sentence,attr"`
}

type monsterLook struct {
Type int `xml:"type,attr"`
Head int `xml:"head,attr"`
Body int `xml:"body,attr"`
Legs int `xml:"legs,attr"`
Feet int `xml:"feet,attr"`
Corpse int `xml:"corpse,attr"`
}

type monsterHealth struct {
Now int `xml:"now,attr"`
Max int `xml:"max,attr"`
}

但我不确定如何读取语音元素

最佳答案

您只是错过了为 Voices 指定 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)
}

playground demo 1

更好的是,删除 monsterVoice 并像这样使用子选择器:

type monster struct {
XMLName xml.Name `xml:"monster"`
....
Voices []monsterSentence `xml:"voices>voice"`
}

然后我们就可以去掉之前demo中那个笨拙的result.Voices.Voices了:

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!

关于xml - 解码 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37629947/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com