Golang XML解析 [英] Golang XML parse
本文介绍了Golang XML解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的XML数据:
<词典版本="0.8"修订版="403605">< grammemes>< grammeme parent ="> POST</grammeme>< grammeme parent ="POST">名词</grammeme></grammemes></dictionary>
我的代码:
type字典struct {XMLName xml.Name`xml:"dictionary"`语法* Grammemes`xml:"grammemes"`}键入Grammemes struct {语法[] * Grammeme`xml:"grammeme"`}键入Grammeme struct {名称字符串`xml:"grammeme"`父字符串`xml:"parent,attr"`}
我得到了Grammeme.Parent属性,但是我没有得到Grammeme.Name.为什么?
解决方案
如果希望字段包含当前元素的内容,则可以使用标记 xml:,chardata"
.标记结构的方法是寻找< grammeme>
子元素.
因此,您可以解码的一组结构是:
type字典struct {XMLName xml.Name`xml:"dictionary"`语法[] Grammeme`xml:"grammemes> grammeme"`}键入Grammeme struct {名称字符串`xml:,chardata"`父字符串`xml:"parent,attr"`}
您可以在此处测试此示例: http://play.golang.org/p/7lQnQOCh0I >
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?
解决方案
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
这篇关于Golang XML解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文