为了账号安全,请及时绑定邮箱和手机立即绑定

去解组 XML

去解组 XML

Go
弑天下 2022-01-17 10:49:23
我目前有以下 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"`}但我不确定如何阅读声音元素
查看完整描述

2 回答

?
慕勒3428872

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!


查看完整回答
反对 回复 2022-01-17
?
函数式编程

TA贡献1807条经验 获得超9个赞

只需使用 xml.Unmarshal(xmlString, data)

这是 xml 解组的完整示例https://golang.org/src/encoding/xml/example_test.go


查看完整回答
反对 回复 2022-01-17
  • 2 回答
  • 0 关注
  • 169 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信