英文:
Golang XML parse
问题
我的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属性。为什么?
英文:
My XML data:
<dictionary version="0.8" revision="403605">
<grammemes>
<grammeme parent="">POST</grammeme>
<grammeme parent="POST">NOUN</grammeme>
</grammemes>
</dictionary>
My code:
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"`
}
I get Grammeme.Parent attribute, but i don't get Grammeme.Name. Why?
答案1
得分: 12
如果你想要一个字段来保存当前元素的内容,你可以使用标签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
英文:
If you want a field to hold the contents of the current element, you can use the tag xml:",chardata"
. The way you've tagged your structure, it is instead looking for a <grammeme>
sub-element.
So one set of structures you could decode into is:
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"`
}
You can test out this example here: http://play.golang.org/p/7lQnQOCh0I
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论