2014-03-26 81 views
8

我的XML數據:Golang 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。爲什麼?

回答

9

如果你想有一個字段來保存當前元素的內容,你可以使用標籤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