去解组XML

时间:2016-06-04 11:55:57

标签: 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" />
    <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 个答案:

答案 0 :(得分:2)

您错过了为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"`
}

然后我们可以摆脱上一个演示中的尴尬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!

答案 1 :(得分:0)

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

即可

以下是xml unmarshalling https://golang.org/src/encoding/xml/example_test.go

的完整示例