Golang : Extract XML attribute data with attr field tag example
This is an additional tutorial for previous tutorial on how to add XML attribute in Golang with struct field tag, but this time we will learn how to extract the XML attribute data into a struct and retrieve the values. The code example below should be self explanatory. Leave comment if you have question.
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"` // here!
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
}
Output :
Total Upload Views : 11286743
Subscriber Count : 698
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+32.4k Golang : How to check if slice or array is empty?
+4.3k Golang : How to deal with configuration data?
+6.3k Golang : Dealing with postal or zip code example
+17.1k Golang : Logging with logrus
+12.6k Golang : Tutorial on loading GOB and PEM files
+28.8k Golang : Remove characters from string example
+12.8k Golang: Pad right or print ending(suffix) zero or spaces in fmt.Printf example
+11.5k Golang : How to calculate the distance between two coordinates using Haversine formula
+20.6k Golang : Print leading(padding) zero or spaces in fmt.Printf?
+21.1k Golang : Read a file into an array or slice example
+20.4k Golang : Convert seconds to minutes and remainder seconds
+6k Golang : Transform lisp or spinal case to Pascal case example