我的XML数据:

<dictionary version="0.8" revision="403605">
    <grammemes>
        <grammeme parent="">POST</grammeme>
        <grammeme parent="POST">NOUN</grammeme>
    </grammemes>
</dictionary>

我的代码:
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"`
}

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

最佳答案

如果希望字段保留当前元素的内容,则可以使用标记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"`
}

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

10-07 17:51