在go语言中使用attr字段标签提取XML属性数据示例
在Golang如何将XML属性数据提取到结构中并检索其值。
看看下面的代码例子。
package main
import (
"encoding/xml"
"fmt"
)
func main() {
chanData, _ := GetChannelData()
fmt.Println("Total Upload Views : ", chanData.Stats.TotalUploadViews)
fmt.Println("Subscriber Count : ", chanData.Stats.SubscriberCount)
}
type Entry struct {
Stats Statistics `xml:"statistics"`
User string `xml:"username"`
}
type Statistics struct {
TotalUploadViews int `xml:"totalUploadViews,attr"` //
SubscriberCount int `xml:"subscriberCount,attr"`
}
func GetChannelData() (*Entry, error) {
rawXML := `<entry>
<yt:statistics lastWebAccess='1990-01-01T00:00:00.000Z' subscriberCount='698' viewCount='0' totalUploadViews='11286743'/>
<yt:username>Adam</yt:username>
</entry>`
XMLbytes := []byte(rawXML)
e := new(Entry)
xml.Unmarshal(XMLbytes, e)
return e, nil
}
输出:
totalUploadViews : 11286743
subscriberCount : 698
相关文章