xml

command
v0.0.0-...-e43910c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 21, 2024 License: CC0-1.0 Imports: 4 Imported by: 0

README

XML

Este é um exemplo de como ler um feed RSS2 e interpretar o retorno para extrair os dados que queremos.

Primeiro criamos as structs que vão conter os dados vindos do XML

// RSS contem a base da estrutura do feed
type RSS struct {
 XMLName     xml.Name `xml:"rss"`
 Version     string   `xml:"version,attr"`
 Title       string   `xml:"channel>title"`
 Link        string   `xml:"channel>link"`
 Description string   `xml:"channel>description"`
 PubDate     string   `xml:"channel>pubDate"`
 ItemList    []Item   `xml:"channel>item"`
}

// Item contem os posts no feed
type Item struct {
 Title       string `xml:"title"`
 Link        string `xml:"link"`
 Description string `xml:"description"`
 Content     string `xml:"encoded"`
 PubDate     string `xml:"pubDate"`
 Comments    string `xml:"comments"`
}

Então baixamos o feed da internet

resp, err := http.Get("http://pizzadedados.com/feed.xml")
if err != nil {
 fmt.Println(err)
 return
}

body, err := io.ReadAll(resp.Body)
if err != nil {
 fmt.Println(err)
}
defer closer(resp.Body)

Finalmente interpretamos os dados o armazenamos na struct

rss := RSS{}
err = xml.Unmarshal(body, &rss)
if err != nil {
 fmt.Println(err)
}

Pronto agora só precisamos exibir os dados

for k, i := range rss.ItemList {
 fmt.Println(k, i.Title)
}

Documentation

The Go Gopher

There is no documentation for this package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL