Golang : Decode XML data from RSS feed
Was looking for a way to decode RSS feed XML data today and here is the code for the tutorial on how to decode XML data from RSS feed with Golang.
Enjoy!
package main
import (
"bytes"
"encoding/xml"
"fmt"
"io/ioutil"
"net/http"
"os"
)
type Rss struct {
Channel Channel `xml:"channel"`
}
type Item struct {
Title string `xml:"title"`
Link string `xml:"link"`
Description string `xml:"description"`
}
type Channel struct {
Title string `xml:"title"`
Link string `xml:"link"`
Description string `xml:"description"`
Items []Item `xml:"item"`
}
func main() {
response, err := http.Get("http://www.thestar.com.my/RSS/Metro/Community/")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer response.Body.Close()
XMLdata, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
rss := new(Rss)
buffer := bytes.NewBuffer(XMLdata)
decoded := xml.NewDecoder(buffer)
err = decoded.Decode(rss)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf("Title : %s\n", rss.Channel.Title)
fmt.Printf("Description : %s\n", rss.Channel.Description)
fmt.Printf("Link : %s\n", rss.Channel.Link)
total := len(rss.Channel.Items)
fmt.Printf("Total items : %v\n", total)
for i := 0; i < total; i++ {
fmt.Printf("[%d] item title : %s\n", i, rss.Channel.Items[i].Title)
fmt.Printf("[%d] item description : %s\n", i, rss.Channel.Items[i].Description)
fmt.Printf("[%d] item link : %s\n\n", i, rss.Channel.Items[i].Link)
}
}
See also : Golang : Get YouTube playlist
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
+5.7k Golang : Extract unicode string from another unicode string example
+20.2k Golang : Secure(TLS) connection between server and client
+5.3k Golang : Shortening import identifier
+13.1k Facebook PHP getUser() returns 0
+42.8k Golang : Get hardware information such as disk, memory and CPU usage
+6.4k Golang : Output or print out JSON stream/encoded data
+12.8k Golang : Handle or parse date string with Z suffix(RFC3339) example
+7.1k Golang : Word limiter example
+13.9k Golang : Chunk split or divide a string into smaller chunk example
+8.7k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+9.5k Golang : List available AWS regions
+5.7k Golang : Grab news article text and use NLP to get each paragraph's sentences