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
+9.6k Golang : Translate language with language package example
+5.3k Golang : Configure crontab to poll every two minutes 8am to 6pm Monday to Friday
+13.2k Golang : Convert spaces to tabs and back to spaces example
+10.4k Golang : Get currencies exchange rates example
+13k Golang : Read from buffered reader until specific number of bytes
+8.2k Golang : Another camera capture GUI application with GTK and OpenCV
+5.9k Javascript : Generate random key with specific length
+5k Golang *File points to a file or directory ?
+8.8k Golang : Write multiple lines or divide string into multiple lines
+5.5k Javascript : How to replace HTML inside <div>?
+20.5k Golang : Clean up null characters from input data
+14.7k Golang : How to check if IP address is in range