Golang XML解析

Kro*_*oid 8 xml go

我的XML数据:

<dictionary version="0.8" revision="403605">
    <grammemes>
        <grammeme parent="">POST</grammeme>
        <grammeme parent="POST">NOUN</grammeme>
    </grammemes>
</dictionary>
Run Code Online (Sandbox Code Playgroud)

我的代码:

type Dictionary struct {
    XMLName xml.Name `xml:"dictionary"`
    Grammemes *Grammemes `xml:"grammemes"`
}

type Grammemes struct {
    Grammemes []*Grammeme `xml:"grammeme"`
}

type Grammeme struct {
    Name string `xml:"grammeme"`
    Parent string `xml:"parent,attr"`
}
Run Code Online (Sandbox Code Playgroud)

我得到Grammeme.Parent属性,但我没有得到Grammeme.Name.为什么?

Jam*_*dge 10

如果希望字段保存当前元素的内容,则可以使用该标记xml:",chardata".您标记结构的方式是寻找<grammeme>子元素.

因此,您可以解码的一组结构是:

type Dictionary struct {
    XMLName   xml.Name   `xml:"dictionary"`
    Grammemes []Grammeme `xml:"grammemes>grammeme"`
}

type Grammeme struct {
    Name   string `xml:",chardata"`
    Parent string `xml:"parent,attr"`
}
Run Code Online (Sandbox Code Playgroud)

您可以在此处测试此示例:http://play.golang.org/p/7lQnQOCh0I